Compare commits
48 Commits
ba919c015e
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b333e0855b | ||
|
|
89ceb2049f | ||
|
|
4fccd5bf43 | ||
|
|
3dd174afa5 | ||
|
|
133becd255 | ||
|
|
df91e7e129 | ||
|
|
025ba2d637 | ||
|
|
94af58b542 | ||
|
|
427827a32b | ||
|
|
b94ef2918c | ||
|
|
0e3cac62a4 | ||
|
|
b7b30575a2 | ||
|
|
0380bc8985 | ||
|
|
33bd002f98 | ||
|
|
3811c5a133 | ||
|
|
4b7db41a97 | ||
|
|
113355c0ef | ||
|
|
16b886081b | ||
|
|
abd6f83535 | ||
|
|
a2706944bd | ||
|
|
532b5b45f3 | ||
|
|
bb8f3263f8 | ||
|
|
a8a0292535 | ||
|
|
c0aaed7d28 | ||
|
|
a657bd0762 | ||
|
|
3eec48d263 | ||
|
|
fc3e5be236 | ||
|
|
83af2dda12 | ||
|
|
833b735b4a | ||
|
|
ed4684c0ed | ||
|
|
d95167d3f3 | ||
|
|
ff59ce8ca6 | ||
|
|
7ca4c99218 | ||
|
|
04a5c2e66c | ||
|
|
645005a5d0 | ||
|
|
140a31982a | ||
|
|
83ae74636b | ||
|
|
45220b9bda | ||
|
|
e36165b5b1 | ||
|
|
bfc9a1bd1d | ||
|
|
f25d034cad | ||
|
|
5cd2fe70a4 | ||
|
|
e1d539a9d5 | ||
|
|
ec713f3da1 | ||
|
|
d09c2c71ce | ||
|
|
2af5f4acb9 | ||
|
|
d53174a1cf | ||
|
|
86442b8c93 |
28
.gitea/workflows/deploy-prod.yml
Normal file
28
.gitea/workflows/deploy-prod.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
name: deploy-frontend-prod
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: prod
|
||||
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 }}
|
||||
SUGGEST_KEY: ${{ secrets.REACT_APP_YANDEX_SUGGEST_KEY }}
|
||||
run: |
|
||||
docker build \
|
||||
--build-arg REACT_APP_API_URL=https://app.nahodka-app.online \
|
||||
--build-arg REACT_APP_YANDEX_GEOCODER_KEY="$GEOCODER_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_MAPS_KEY="$MAPS_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_SUGGEST_KEY="$SUGGEST_KEY" \
|
||||
--build-arg REACT_APP_WS_ERROR_QUEUE=true \
|
||||
-t nakhodka-frontend:latest \
|
||||
-t nakhodka-frontend:${{ github.ref_name }} .
|
||||
- name: Restart frontend
|
||||
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d frontend
|
||||
- name: Cleanup
|
||||
run: docker image prune -f
|
||||
@@ -18,6 +18,7 @@ jobs:
|
||||
--build-arg REACT_APP_YANDEX_GEOCODER_KEY="$GEOCODER_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_MAPS_KEY="$MAPS_KEY" \
|
||||
--build-arg REACT_APP_YANDEX_SUGGEST_KEY="$SUGGEST_KEY" \
|
||||
--build-arg REACT_APP_WS_ERROR_QUEUE=true \
|
||||
-t nakhodka-frontend:latest \
|
||||
-t nakhodka-frontend:${{ github.sha }} .
|
||||
- name: Restart frontend
|
||||
|
||||
34
.github/workflows/ci.yml
vendored
Normal file
34
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master]
|
||||
push:
|
||||
branches: [master]
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
checks:
|
||||
name: lint, typecheck, test, build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
CI: true
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
# .npmrc задаёт legacy-peer-deps=true (react-scripts 5 + TypeScript 5)
|
||||
- run: npm ci
|
||||
|
||||
- run: npm run lint
|
||||
- run: npm run typecheck
|
||||
- run: npm run test:ci
|
||||
- run: npm run build
|
||||
207
README.md
207
README.md
@@ -1,9 +1,10 @@
|
||||
# Находка
|
||||
|
||||
Платформа для поиска потерянных вещей и питомцев. SPA на React 18 с JWT-аутентификацией
|
||||
и автоматическим обновлением токена, чатом на WebSocket (STOMP/SockJS), картами Яндекса,
|
||||
загрузкой изображений, админ-панелью рекламы и модерации объявлений, i18n (ru/en) и
|
||||
светлой/тёмной темой.
|
||||
и автоматическим обновлением токена, чатом на WebSocket (STOMP/SockJS) с фото и видео,
|
||||
картами Яндекса, загрузкой изображений, защитой номера телефона от сбора, админ-панелью
|
||||
рекламы и модерации объявлений, i18n (ru/en), светлой/тёмной темой и отдельной
|
||||
десктопной раскладкой (от 900 px).
|
||||
|
||||
---
|
||||
|
||||
@@ -54,7 +55,7 @@ npm run build # production-сборка в build/
|
||||
| `REACT_APP_YANDEX_MAPS_KEY` | для карты | — | Публичный ключ Яндекс.Карт, подставляется в `public/index.html` |
|
||||
| `REACT_APP_SUPPORT_EMAIL` | нет | есть значение по умолчанию | Почта поддержки в модалке «Поддержка» |
|
||||
| `REACT_APP_YANDEX_SUGGEST_KEY` | нет | — | «API Геосаджеста»: подсказки адреса; без него подсказки идут из Геокодера |
|
||||
| `REACT_APP_WS_ERROR_QUEUE` | нет | `false` | `true` — подписываться на `/user/queue/errors` (ошибки отправки сообщений чата). Включать **только после деплоя** бэкенда из ветки backend-review: старый бэкенд отклоняет эту подписку и закрывает STOMP-соединение |
|
||||
| `REACT_APP_WS_ERROR_QUEUE` | нет | `false` | `true` — подписываться на `/user/queue/errors` (ошибки отправки сообщений чата). Бэкенд из `master` эту подписку поддерживает; со старым бэкендом (до backend-review) не включать — он отклоняет подписку и закрывает STOMP-соединение |
|
||||
|
||||
> **Безопасность.** Ключи Яндекса — публичные, но попадание реального `.env` в git
|
||||
> означает утечку в историю коммитов. Если файл уже коммитился, перевыпустите ключи:
|
||||
@@ -108,6 +109,17 @@ CRA типы не проверяет — их вырезает babel, а про
|
||||
|
||||
Перед коммитом стоит прогнать все четыре проверки: `lint`, `typecheck`, `test:ci`, `build`.
|
||||
|
||||
### CI (GitHub Actions)
|
||||
|
||||
`.github/workflows/ci.yml` запускается на каждый PR в `master` и на push в `master`:
|
||||
Node 22, `npm ci`, затем те же четыре проверки с `CI=true` (в этом режиме
|
||||
предупреждения сборки CRA считаются ошибками). `REACT_APP_*` не задаются — для
|
||||
проверок они не нужны. Деплой по-прежнему делает `.gitea/workflows/deploy.yml`.
|
||||
|
||||
Рекомендуется включить защиту ветки: GitHub → Settings → Branches → правило для
|
||||
`master` → *Require status checks to pass before merging* → выбрать проверку
|
||||
`lint, typecheck, test, build` (появится в списке после первого запуска workflow).
|
||||
|
||||
---
|
||||
|
||||
## 5. Структура проекта
|
||||
@@ -123,7 +135,10 @@ src/
|
||||
│ ├── apiClient.jsx # apiFetch: Authorization + refresh токена по 401
|
||||
│ ├── adminAdsApi.js # Кампании, реклама, фуллскрин-реклама
|
||||
│ ├── adminContentApi.js # Админские объявления: список, статус, удаление
|
||||
│ └── adsApi.js # Фуллскрин-реклама, пресigned-выгрузка видео
|
||||
│ ├── adsApi.js # Фуллскрин-реклама, presigned-выгрузка видео
|
||||
│ ├── apiErrors.js # ApiError, readApiError, describeApiError
|
||||
│ ├── phoneApi.js # Показ номера: задача proof-of-work → номер
|
||||
│ └── searchApi.js # Подсказки поиска
|
||||
│
|
||||
├── config/
|
||||
│ ├── authConstants.js # API_URL
|
||||
@@ -137,18 +152,26 @@ src/
|
||||
│
|
||||
├── stores/
|
||||
│ ├── activeChatStore.js # Активный чат
|
||||
│ └── chatPostStore.js # Кэш «объявление ↔ чат»
|
||||
│ └── chatPostStore.js # Кэш «объявление ↔ чат» (localStorage); удалённое объявление помечается removed
|
||||
│
|
||||
├── hooks/ # см. раздел 9
|
||||
│
|
||||
├── utils/
|
||||
│ ├── adSession.js # ID рекламной сессии (устойчив к запрету localStorage)
|
||||
│ ├── campaignStatus.js # Статусы кампаний
|
||||
│ ├── chatDisplay.jsx # Данные для списка чатов
|
||||
│ ├── compressImage.js # Сжатие JPEG до 1200px
|
||||
│ ├── chatDisplay.jsx # Данные для списка чатов: заголовок, превью («Фото»/«Видео»), время
|
||||
│ ├── compressImage.js # Сжатие фото до 1920px, WebP (или JPEG в Safari); ≤ 300 КБ и ≤ 1920px — без изменений
|
||||
│ ├── escapeHtml.js # Экранирование для HTML-строк (балуны Яндекс.Карт)
|
||||
│ ├── formatPhone.js # Маска +7 (___) ___-__-__
|
||||
│ ├── foundAt.js # Дата «Найдено»: closedAt с бэкенда или запомненная на устройстве
|
||||
│ ├── passwordPolicy.js # Пароль: от 8 символов, ≤ 72 байт
|
||||
│ ├── proofOfWork.js # Решение задачи ALTCHA (SHA-256) для показа номера
|
||||
│ ├── relativeTime.js # «5 минут назад»
|
||||
│ ├── safeUrl.js # Только абсолютные http(s)-ссылки
|
||||
│ ├── timezone.js, timezoneFetch.js # Заголовок X-Timezone ко всем запросам
|
||||
│ ├── validatePostForm.js # Валидация формы объявления
|
||||
│ ├── withAds.js # Рекламная обёртка
|
||||
│ ├── yandexGeo.js # Подсказки адреса и геокодирование Яндекса
|
||||
│ └── ymapsApi.js # Ожидание window.ymaps с таймаутом
|
||||
│
|
||||
├── pages/
|
||||
@@ -166,19 +189,21 @@ src/
|
||||
│ ├── feed/ FeedTopBar.tsx, FeedContent, FeedSearchBar, PullToRefresh, RewardPopup
|
||||
│ ├── nav/ BottomNav.jsx, Sidebar.jsx
|
||||
│ ├── layout/ AppTopBar.jsx
|
||||
│ ├── chat/ ChatHeader, ChatInputBar, ChatListItem, MessageBubble
|
||||
│ ├── chat/ ChatHeader, ChatInputBar, ChatListItem, ChatPostMeta, MessageBubble, ChatPhotoViewer
|
||||
│ ├── desktop/ DesktopChats, DesktopSidebar, DesktopFeedHeader, DesktopMapView, DesktopIcons
|
||||
│ ├── reviews/ RatingSummary, ReviewCard, ReviewForm, StarRating
|
||||
│ ├── profile/ Profile, ProfileAvatar, ProfileFormFields, ProfileModal, profileValidation
|
||||
│ ├── admin/ PostsTab, AdvertisingCreate/EditModal, CampaignCreate/EditModal, ...
|
||||
│ ├── landing/ Hero, Navbar, StepsSection, RadarBeacon, FinalCta, Footer, Icon
|
||||
│ ├── icons/ NavIcons + Calendar/Close/Globe/Menu/Moon/Phone/Pin/Sun/Trash
|
||||
│ └── … AuthModal, Toast, MapView, PostDetailModal, AdCard, AdSlot, ...
|
||||
│ └── … AuthModal, Toast, MapView, PostDetailModal, GuideModal, GuestGuideBanner, AdCard, AdSlot, ...
|
||||
│
|
||||
├── styles/
|
||||
│ ├── index.css # Точка входа CSS
|
||||
│ ├── base.css # Переменные, сброс, keyframes
|
||||
│ ├── layout.css, sidebar.css, card.css, modal.css, ui.css
|
||||
│ └── chat.css, reviews.css, rules.css, admin.css, NakhodkaLanding.css
|
||||
│ ├── chat.css, desktop.css, guide.css
|
||||
│ └── reviews.css, rules.css, admin.css, NakhodkaLanding.css
|
||||
│
|
||||
└── locales/
|
||||
├── ru.json
|
||||
@@ -194,13 +219,19 @@ src/
|
||||
| `/` | `NakhodkaLanding` | публичный лендинг |
|
||||
| `/feed` | `MainFeed` | лента (главная) |
|
||||
| `/reviews` | `ReviewsPage` | отзывы о площадке |
|
||||
| `/chats` | `ChatListPage` | список чатов |
|
||||
| `/chats/:chatId` | `ChatPage` | чат |
|
||||
| `/chats` | `ChatListPage` / `DesktopChats` | список чатов |
|
||||
| `/chats/new` | `ChatPage` / `DesktopChats` | черновик чата: переписки ещё нет, чат создаётся с первым сообщением (данные — в `location.state`) |
|
||||
| `/chats/:chatId` | `ChatPage` / `DesktopChats` | чат |
|
||||
| `/admin/ads` | `AdminAdsPage` | только `isAdmin` (иначе редирект на `/feed`) |
|
||||
| `*` | `NakhodkaLanding` | 404-fallback |
|
||||
|
||||
Провайдеры: `ThemeProvider` → `AuthProvider` → `BrowserRouter`.
|
||||
|
||||
Чаты на экране от 900 px (`useIsDesktop`) — двухпанельный мессенджер
|
||||
`DesktopChats` (список слева, открытый `ChatPage` справа, список не
|
||||
перезагружается при переключении); на телефоне — отдельные страницы
|
||||
`ChatListPage` и `ChatPage`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Ключевые компоненты
|
||||
@@ -215,16 +246,31 @@ src/
|
||||
|
||||
### `PostOnFeed.jsx`
|
||||
|
||||
Карточка объявления: фото, бейджи категории/типа/статуса, заголовок, описание,
|
||||
адрес, дата, телефон, кнопка карты и «Написать». Для владельца — редактирование,
|
||||
удаление, отметка «найдено».
|
||||
Карточка объявления: фото (карусель), бейджи категории/типа/статуса, заголовок,
|
||||
описание, адрес, дата, кнопка карты и «Написать». Для владельца — редактирование,
|
||||
удаление, отметка «найдено». Номер телефона в ленту не приходит: если автор дал
|
||||
согласие (`phoneVisible`), показывается кнопка «Показать номер» (`useRevealPhone`,
|
||||
proof-of-work); автор видит свой номер сразу. У закрытого объявления кнопки нет.
|
||||
У объявления с контрольными вопросами (`verificationQuestions`) кнопка «Написать» становится
|
||||
«Я нашёл» (у потери) или «Это моё» (у находки): черновик чата показывает форму ответов (`ClaimForm`), чат создаётся вместе с ними
|
||||
(`POST /api/v1/posts/:id/claim`), а писать дальше и видеть номер заявитель может, когда автор
|
||||
подтвердит ответы (`VerificationPanel`, `POST /api/v1/chats/:id/verification`). В каждом чате —
|
||||
плашка «не переводите предоплату» (`ChatSafetyNotice`) и отметка о новом аккаунте собеседника;
|
||||
под сообщением с просьбой о предоплате, данных карты или коде из СМС получатель видит
|
||||
предупреждение (`message.fraudSignal` с бэкенда).
|
||||
Пропсы `compact` (без адреса и даты — для карты) и `hideContact` (без «Написать» —
|
||||
карточка открыта из самого чата).
|
||||
|
||||
### `CreateUpdatePost.jsx`
|
||||
|
||||
Модалка создания/редактирования. Переключатель Потеря/Находка, заголовок,
|
||||
описание, фото (сжатие на клиенте), категория, карта Яндекса с меткой и обратным
|
||||
геокодированием, адрес, телефон с маской, чекбокс правил. Валидация —
|
||||
`validatePostForm`. С пропом `adminMode` шлёт `PUT /api/v1/admin/posts/{id}`.
|
||||
описание, фото (сжатие на клиенте, на десктопе — и перетаскиванием, `useFileDropZone`),
|
||||
категория, карта Яндекса с меткой и обратным геокодированием, адрес, телефон с маской
|
||||
(подставляется из профиля) и галочка согласия на показ номера (`phoneVisible`: без неё
|
||||
номер не отправляется и не хранится), вознаграждение (только у потерь), до трёх контрольных
|
||||
вопросов (JSON-массивом в `verificationQuestions`) и блок «Как не попасться мошенникам», чекбокс правил.
|
||||
Валидация — `validatePostForm`. С пропом `adminMode` шлёт `PUT /api/v1/admin/posts/{id}`
|
||||
и не меняет согласие автора.
|
||||
|
||||
### `FeedContent.jsx` / `FeedTopBar.tsx` / `PullToRefresh.jsx`
|
||||
|
||||
@@ -237,6 +283,31 @@ cleanup класса активности.
|
||||
если он не загрузился. Первая загрузка маркеров идёт по фактическим границам
|
||||
карты, а не по событию `load` (которого у `ymaps.Map` в 2.1 нет).
|
||||
|
||||
### Чат: `ChatPage.jsx`, `components/chat/*`
|
||||
|
||||
- `ChatHeader` — фото и заголовок объявления, строка `ChatPostMeta` (тип, город,
|
||||
«Закрыто» / «Объявление удалено»). Заголовок и кнопка ⓘ открывают объявление в
|
||||
`PostDetailModal` (полная карточка, «Показать на карте» — переход на
|
||||
`/feed?view=map&post=…&lat=…&lng=…`); удалённое или снятое объявление (404) —
|
||||
понятное сообщение.
|
||||
- `ChatListItem` — та же строка `ChatPostMeta` под заголовком, чтобы различать
|
||||
чаты по похожим объявлениям.
|
||||
- `ChatInputBar` — скрепка (фото или видео), вставка картинок из буфера, превью
|
||||
выбранного с крестиком, у видео — длительность и процент загрузки.
|
||||
- `MessageBubble` — фото сеткой (одно — в своих пропорциях), видео плеером с
|
||||
обложкой; пока видео обрабатывается — заглушка, при ошибке — сообщение. Размеры
|
||||
с бэкенда резервируют место, лента не прыгает.
|
||||
- `ChatPhotoViewer` — просмотр фото на весь экран: стрелки, свайп, Esc.
|
||||
- Ссылки на вложения временные: при ошибке загрузки фото/видео `ChatPage` один
|
||||
раз берёт свежие (`/attachments/{id}/url`).
|
||||
|
||||
### Десктоп: `components/desktop/*`
|
||||
|
||||
От 900 px — своя раскладка: `DesktopSidebar` (навигация, логотип ведёт на `/feed`,
|
||||
пункт «О проекте» — на лендинг), `DesktopFeedHeader` (переключатель «Все / Потери /
|
||||
Находки»), `DesktopMapView` (карта со списком объявлений видимой области),
|
||||
`DesktopChats` (мессенджер). Стили — `desktop.css`.
|
||||
|
||||
### `AdminAdsPage.jsx` + `components/admin/PostsTab.jsx`
|
||||
|
||||
Админ-панель: вкладки «Рекламные кампании» и «Все объявления».
|
||||
@@ -296,14 +367,16 @@ cleanup класса активности.
|
||||
| `useFeedPosts.jsx` | Лента с пагинацией, request-id guard, дедупликация |
|
||||
| `useCityFeed.jsx` | Лента по городу |
|
||||
| `useSearchPosts.js` | Поиск с дебаунсом |
|
||||
| `useMyPosts.jsx` | Мои объявления: `GET /api/v1/users/{id}/posts` (все страницы), на старом бэкенде — откат на `GET /api/v1/posts/{id}`; с токеном, поэтому видны и неопубликованные (метки «На модерации»/«Отклонено») |
|
||||
| `useMyPosts.jsx` | Мои объявления: `GET /api/v1/users/{id}/posts` (все страницы); с токеном, поэтому видны и неопубликованные (метки «На модерации»/«Отклонено») |
|
||||
| `useFeedActions.jsx` | Удаление и отметка «найдено» + `error`/`clearError` |
|
||||
| `usePostMutation.js` | Создание/обновление (обычное и `adminMode`) |
|
||||
| `useDeletePost.js`, `usePostStatus.js` | Точечные мутации |
|
||||
| `useImageUpload.js` | Выбор, сжатие, превью изображения |
|
||||
| `useImageUpload.js` | Выбор, сжатие, превью изображений; `clearImages` — сброс после отправки |
|
||||
| `useFileDropZone.js` | Перетаскивание файлов (форма объявления, аватар); файл, брошенный мимо зоны, не открывается браузером |
|
||||
| `useRevealPhone.js` | «Показать номер»: задача → решение (`utils/proofOfWork.js`) → номер; 429 и ошибки — текстом |
|
||||
| `useModals.jsx` | Управление модалками |
|
||||
| `useInfiniteScroll.jsx` | Бесконечная прокрутка с cleanup `IntersectionObserver` |
|
||||
| `useCities.js`, `useClickOutside.jsx`, `useIsDesktop.js` | Вспомогательные |
|
||||
| `useCities.js`, `useCityOptions.js`, `useClickOutside.jsx`, `useIsDesktop.js`, `useHideOnScroll.js`, `useProfileData.js` | Вспомогательные |
|
||||
|
||||
### Реклама
|
||||
|
||||
@@ -321,7 +394,9 @@ cleanup класса активности.
|
||||
| `useStompClient.js` | Общий STOMP-клиент: reconnect, истекающий токен обновляется в `beforeConnect`, после отказа CONNECT — принудительный refresh (не чаще раза в минуту), мёртвая сессия останавливает переподключения |
|
||||
| `useChatSocket.js` | Подписка на чат, отправка сообщений, ошибки отправки из `/user/queue/errors` (флаг `REACT_APP_WS_ERROR_QUEUE`) |
|
||||
| `useUnreadSocket.js` | Непрочитанные |
|
||||
| `useChats.js` | Список чатов, создание, сообщения (request-id guard) |
|
||||
| `useChats.js` | Список чатов, создание, сообщения (request-id guard); `sendPhotoMessage` (multipart), `sendVideoMessage` (ссылка → PUT в хранилище с прогрессом → подтверждение), `refreshAttachmentUrl` |
|
||||
| `useChatList.js` | Список чатов для мобильной и десктопной версии: загрузка, обновление по WS, удаление с подтверждением |
|
||||
| `useVideoAttachment.js` | Выбранное видео: формат (MP4/MOV/WebM/3GP), ≤ 100 МБ, ≤ 60 с по метаданным, превью |
|
||||
| `useContactSeller.js` | Создание/получение чата с продавцом |
|
||||
| `useDeleteChat.js` | Удаление чата |
|
||||
|
||||
@@ -369,13 +444,21 @@ cleanup класса активности.
|
||||
| `GET` | `/api/v1/posts/search/suggest?q=` | Подсказки поиска |
|
||||
| `GET` | `/api/v1/posts/cities` | Список городов |
|
||||
| `GET` | `/api/v1/posts/map?minLat&maxLat&minLng&maxLng&…` | Маркеры в границах карты |
|
||||
| `GET` | `/api/v1/posts/detail/:postId` | Карточка объявления |
|
||||
| `GET` | `/api/v1/users/:userId/posts?page=&size=` | Объявления пользователя (`Page`; новый бэкенд) |
|
||||
| `GET` | `/api/v1/posts/:userId` | Объявления пользователя — устаревший маршрут, запасной для старого бэкенда |
|
||||
| `POST` | `/api/v1/posts` | Создать (`FormData`); новый бэкенд отвечает 201 с `PostResponse` |
|
||||
| `GET` | `/api/v1/posts/:postId` | Одно объявление (`/detail/:postId` — прежний адрес, алиас) |
|
||||
| `GET` | `/api/v1/users/:userId/posts?page=&size=` | Объявления пользователя (`Page`); владельцу — и неопубликованные |
|
||||
| `POST` | `/api/v1/posts` | Создать (`FormData`); ответ 201 с `PostResponse` и `Location` |
|
||||
| `PUT` | `/api/v1/posts/:id` | Обновить (`FormData`) |
|
||||
| `DELETE` | `/api/v1/posts/:id` | Удалить |
|
||||
| `PATCH` | `/api/v1/posts/:postId/status` | Статус `ACTIVE` / `CLOSED` |
|
||||
| `GET` | `/api/v1/posts/:id/phone/challenge` | Задача proof-of-work для показа номера (без входа) |
|
||||
| `POST` | `/api/v1/posts/:id/claim` | «Я нашёл» / «Это моё»: `{ answers }` на контрольные вопросы → чат-заявка (201) |
|
||||
| `POST` | `/api/v1/posts/:id/phone` | `{ salt, number, signature }` → `{ phone }`; 429 — лимит или бан |
|
||||
|
||||
Автор объявления — поле `userLogin` (прежнее `userEmail` удалено). `phone` приходит
|
||||
только автору; остальным — `phoneVisible` и кнопка «Показать номер». Форма шлёт
|
||||
`phoneVisible=true|false`, номер — только с согласием. `closedAt` — время закрытия:
|
||||
закрытое объявление неделю видно в ленте с отметкой «Найдено» (`utils/foundAt.js`),
|
||||
потом бэкенд его удаляет.
|
||||
|
||||
### Профиль
|
||||
|
||||
@@ -388,13 +471,25 @@ cleanup класса активности.
|
||||
|
||||
| Метод | Endpoint | Назначение |
|
||||
|-------|----------|-----------|
|
||||
| `GET` | `/api/v1/chats` | Список чатов |
|
||||
| `POST` | `/api/v1/chats/with/:otherUserId` | Создать/получить чат (`{ postId }`) |
|
||||
| `GET` | `/api/v1/chats/:chatId/messages` | Сообщения |
|
||||
| `POST` | `/api/v1/chats/:chatId/messages` | Отправить |
|
||||
| `GET` | `/api/v1/chats` | Список чатов: `post {id, title, images, type, status, city}`, последнее сообщение, `lastMessageAttachments` / `lastMessageAttachmentKind`, непрочитанные |
|
||||
| `GET` | `/api/v1/chats/with/:otherUserId?postId=` | Найти чат по объявлению; 404 — переписки ещё нет (открывается черновик `/chats/new`) |
|
||||
| `POST` | `/api/v1/chats/with/:otherUserId/messages?postId=` | Первое сообщение `{ content }`: создаёт чат |
|
||||
| `GET` | `/api/v1/chats/:chatId` | Один чат: `verificationStatus`, `claimantId`, `otherUserCreatedAt` |
|
||||
| `POST` | `/api/v1/chats/:chatId/verification` | Автор объявления: `{ approved }` → сообщение `kind: VERIFICATION` |
|
||||
| `GET` | `/api/v1/chats/:chatId/messages` | Сообщения (`attachments` у каждого) |
|
||||
| `POST` | `/api/v1/chats/:chatId/messages` | Сообщение с фото: `FormData` (`content`, `files` ×≤10) |
|
||||
| `POST` | `/api/v1/chats/:chatId/videos/upload-url` | `{ contentType, sizeBytes }` → `{ uploadUrl, sourceKey }` |
|
||||
| `PUT` | `uploadUrl` (MinIO) | Файл видео с тем же `Content-Type` (через `XMLHttpRequest` ради прогресса) |
|
||||
| `POST` | `/api/v1/chats/:chatId/videos` | `{ sourceKey, content }` → сообщение с видео в `PROCESSING` |
|
||||
| `GET` | `/api/v1/chats/:chatId/attachments/:id/url` | Свежие `url` / `posterUrl` вложения |
|
||||
| `POST` | `/api/v1/chats/:chatId/read` | Отметить прочитанным |
|
||||
| `DELETE` | `/api/v1/chats/:chatId` | Удалить чат |
|
||||
|
||||
Текстовые сообщения уходят по STOMP (`/app/chat.send`), фото и видео — по REST.
|
||||
Вложение: `{ id, kind: PHOTO|VIDEO, status: READY|PROCESSING|FAILED, url, posterUrl,
|
||||
width, height, durationMs }`; ссылки — временные presigned на MinIO (6 ч). Видео
|
||||
отправляется отдельным сообщением, без фото; в черновике чата вложения недоступны.
|
||||
|
||||
### Отзывы
|
||||
|
||||
| Метод | Endpoint | Тело |
|
||||
@@ -406,7 +501,7 @@ cleanup класса активности.
|
||||
|
||||
| Метод | Endpoint | Назначение |
|
||||
|-------|----------|-----------|
|
||||
| `GET` | `/api/v1/files/:filename` | Изображение по имени |
|
||||
| `GET` | `/api/v1/files/:filename` | Изображение по имени (вложения чатов здесь не отдаются) |
|
||||
| `GET` | `/api/fullscreen-ad` | Текущая фуллскрин-реклама |
|
||||
| `GET` | `/api/ads/next` | Следующая реклама: `{advertisingId, type, mediaUrl, targetUrl, impressionToken}` или 204; заголовок `X-Session-Id` |
|
||||
| `POST` | `/api/ads/impression`, `/api/ads/click` | `{advertisingId, sessionId, token}` — `token` = `impressionToken` |
|
||||
@@ -431,7 +526,7 @@ STOMP поверх SockJS: `${REACT_APP_API_URL}/ws` (токен передаё
|
||||
|
||||
| Назначение | Путь |
|
||||
|-----------|------|
|
||||
| Подписка на чат | `/topic/chat/{chatId}` |
|
||||
| Подписка на чат | `/topic/chat/{chatId}` — новые сообщения и обновлённые (видео обработалось); `ChatPage` заменяет сообщение с тем же `id` |
|
||||
| Подписка на непрочитанные | `/topic/user/{userId}/unread` |
|
||||
| Ошибки отправки (флаг `REACT_APP_WS_ERROR_QUEUE`) | `/user/queue/errors` |
|
||||
| Отправка сообщения | `/app/chat.send` |
|
||||
@@ -581,7 +676,7 @@ CONNECT — с заголовком `Authorization: Bearer <access>`; refresh-JW
|
||||
index.css → base.css → layout.css → sidebar.css → card.css → modal.css → ui.css
|
||||
```
|
||||
|
||||
Дополнительно подключаются в компонентах: `chat.css` (`App.js`),
|
||||
Дополнительно подключаются в компонентах: `chat.css` и `desktop.css` (`App.js`),
|
||||
`reviews.css`, `rules.css`, `admin.css`, `NakhodkaLanding.css`.
|
||||
|
||||
CSS-переменные в `base.css`:
|
||||
@@ -602,6 +697,7 @@ CSS-переменные в `base.css`:
|
||||
|
||||
| Брейкпоинт | Что меняется |
|
||||
|------------|-------------|
|
||||
| `≥ 900px` | Десктопная раскладка (`desktop.css`, `useIsDesktop`): левая навигация, двухпанельные чаты, карта со списком |
|
||||
| `≤ 900px` | Правый сайдбар скрывается, навигация внизу |
|
||||
| `≤ 768px` | Компактные отступы и кнопки |
|
||||
| `≤ 600px` | Модалки на всю ширину |
|
||||
@@ -620,9 +716,26 @@ CSS-переменные в `base.css`:
|
||||
заполняет форму → клиентское сжатие фото → `POST /api/v1/posts` (`FormData`) →
|
||||
лента обновляется.
|
||||
|
||||
**Поиск и чат.** «Написать» → `POST /api/v1/chats/with/:otherUserId` →
|
||||
переход на `/chats/:chatId` → подписка на `/topic/chat/{chatId}` →
|
||||
сообщения в реальном времени.
|
||||
**Поиск и чат.** «Написать» → `GET /api/v1/chats/with/:otherUserId?postId=` → есть
|
||||
переписка — `/chats/:chatId`, нет — черновик `/chats/new`, чат создаётся первым
|
||||
сообщением → подписка на `/topic/chat/{chatId}` → сообщения в реальном времени.
|
||||
В шапке чата видно, к какому объявлению он относится, ⓘ открывает объявление.
|
||||
|
||||
**Фото и видео в чате.** Скрепка → до 10 фото (сжатие на клиенте) → одним
|
||||
`POST /api/v1/chats/:chatId/messages`. Видео (одно, ≤ 100 МБ, ≤ 60 с) → ссылка на
|
||||
загрузку → `PUT` прямо в MinIO с процентом → подтверждение → в ленте заглушка
|
||||
«обрабатывается», через несколько секунд по сокету приходит готовый плеер.
|
||||
|
||||
**Первый визит.** Гость открывает ленту → через секунду появляется подсказка
|
||||
«Ты здесь впервые?» (`GuestGuideBanner`: на телефоне сверху, смахивается вверх; на
|
||||
десктопе справа внизу, закрывается крестиком) → «Как пользоваться» открывает
|
||||
`GuideModal` — шесть шагов (лента и карта, объявление, чат, номер, «вернулось») и правила безопасности. Закрытая или открытая подсказка
|
||||
больше не показывается (`localStorage`, ключ `nakhodka:guideBannerDismissed`).
|
||||
Инструкция всегда доступна из меню: пункт «Инструкция» в мобильном меню и в
|
||||
десктопной навигации.
|
||||
|
||||
**Показ номера.** «Показать номер» → `GET …/phone/challenge` → браузер решает задачу
|
||||
(доли секунды) → `POST …/phone` → номер-ссылка `tel:`.
|
||||
|
||||
**Карта.** `useYandexMap` ждёт `window.ymaps` (с таймаутом и ошибкой вместо
|
||||
вечного спиннера), клик по карте ставит метку, drag метки и клик переводят
|
||||
@@ -647,13 +760,21 @@ request-id от гонок.
|
||||
- **Бэкенд до ветки backend-review** отвечал `500` на битый JSON и неверные
|
||||
параметры; новый отдаёт корректные 400/401/403/404/413/422. Фронт разбирает
|
||||
оба варианта (`api/apiErrors.js`).
|
||||
- **Совместимость со старым бэкендом.** Всё, кроме подписки `/user/queue/errors`,
|
||||
работает и с ним: новые маршруты (`/users/{id}/posts`, статистика кампаний)
|
||||
имеют запасной путь или понятное сообщение. Подписку включает
|
||||
`REACT_APP_WS_ERROR_QUEUE=true` после деплоя.
|
||||
- **Фронт и бэкенд деплоятся парой, бэкенд — первым.** Фронт из `master` рассчитан на
|
||||
бэкенд из `master`: одно объявление по `GET /api/v1/posts/{id}`, показ номера по
|
||||
proof-of-work, вложения в чатах. Со старым бэкендом не работают «Мои объявления»,
|
||||
карточка с карты, номер телефона и отправка фото/видео.
|
||||
- **`Retry-After`** виден фронту, только если бэкенд отдаёт его в
|
||||
`Access-Control-Expose-Headers` (ветка `claude/posts-api-contract`); иначе
|
||||
на 429 показывается общий текст «повторите позже».
|
||||
`Access-Control-Expose-Headers` (бэкенд из `master` отдаёт); иначе на 429
|
||||
показывается общий текст «повторите позже».
|
||||
- **Видео из чата грузится прямо в MinIO**: адрес MinIO должен быть доступен
|
||||
браузеру, а CORS хранилища — разрешать `PUT` с домена сайта.
|
||||
- **Видео HEVC с iPhone** Chrome не читает, поэтому длительность до загрузки не
|
||||
проверяется — видео длиннее минуты отклонит бэкенд после загрузки («Не удалось
|
||||
обработать видео»).
|
||||
- **Прокрутка при открытии чата**: лента не всегда доходит до самого низа
|
||||
(замечено в панели предпросмотра, в том числе в чатах без вложений). Когда
|
||||
появляются превью выбранных фото, лента прижимается к низу.
|
||||
- **CSP** не настроена: для неё нужно перечислить домены API, MinIO и
|
||||
Яндекс.Карт. В `nginx.conf` есть базовые заголовки (`nosniff`,
|
||||
`Referrer-Policy`, `X-Frame-Options`), сжатие и `no-cache` для `index.html`.
|
||||
|
||||
@@ -12,7 +12,23 @@
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/apple-touch-icon.png" />
|
||||
<script defer src="https://api-maps.yandex.ru/2.1/?apikey=%REACT_APP_YANDEX_MAPS_KEY%&lang=ru_RU" type="text/javascript"></script>
|
||||
<!--
|
||||
Шрифты Google — без блокировки рендера. Раньше они подключались через
|
||||
@import в CSS-бандле: бандл приложения (defer) ждал этот CSS, и при
|
||||
медленном или недоступном fonts.googleapis.com страница оставалась белой
|
||||
20–30 секунд. Теперь стили грузятся как media="print" и включаются по
|
||||
onload; до этого текст рисуется системным шрифтом (display=swap).
|
||||
-->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800;900&family=Literata:opsz,wght@7..72,400;7..72,500;7..72,600;7..72,700&family=Inter:wght@400;500;600;700&display=swap" media="print" onload="this.media='all'" />
|
||||
<noscript><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800;900&family=Literata:opsz,wght@7..72,400;7..72,500;7..72,600;7..72,700&family=Inter:wght@400;500;600;700&display=swap" /></noscript>
|
||||
<!--
|
||||
API Яндекс.Карт — async, а не defer: defer-скрипты выполняются по порядку,
|
||||
и бандл приложения ждал бы загрузку карт. Код карты сам дожидается
|
||||
window.ymaps (src/utils/ymapsApi.js → whenYmapsReady).
|
||||
-->
|
||||
<script async src="https://api-maps.yandex.ru/2.1/?apikey=%REACT_APP_YANDEX_MAPS_KEY%&lang=ru_RU" type="text/javascript"></script>
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
|
||||
23
src/App.js
23
src/App.js
@@ -1,6 +1,6 @@
|
||||
// src/App.jsx
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom';
|
||||
import { BrowserRouter, Routes, Route, useLocation, Navigate, useParams } from 'react-router-dom';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import { ThemeProvider } from './context/ThemeContext';
|
||||
import { useAuthContext } from './context/AuthContext';
|
||||
@@ -12,7 +12,11 @@ import ChatPage from './pages/ChatPage';
|
||||
import ChatListPage from './pages/ChatListPage';
|
||||
import ReviewsPage from './pages/ReviewsPage';
|
||||
import AdminAdsPage from './pages/AdminAdsPage';
|
||||
import DesktopChats from './components/desktop/DesktopChats';
|
||||
import { useIsDesktop } from './hooks/useIsDesktop';
|
||||
import './styles/chat.css';
|
||||
// Десктопный слой (>= 900px) — последним, чтобы переопределять базовые стили.
|
||||
import './styles/desktop.css';
|
||||
|
||||
function ScrollToTop() {
|
||||
const { pathname } = useLocation();
|
||||
@@ -48,6 +52,17 @@ function AdminRoute({ children }) {
|
||||
return children;
|
||||
}
|
||||
|
||||
// Чаты: на десктопе — один двухпанельный мессенджер для всех трёх адресов
|
||||
// (список не перемонтируется при переключении чатов), на мобильном —
|
||||
// прежние отдельные страницы списка и переписки.
|
||||
function ChatsRoute() {
|
||||
const isDesktop = useIsDesktop();
|
||||
const { chatId } = useParams();
|
||||
const { pathname } = useLocation();
|
||||
if (isDesktop) return <DesktopChats />;
|
||||
return chatId || pathname === '/chats/new' ? <ChatPage /> : <ChatListPage />;
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
@@ -59,9 +74,9 @@ function App() {
|
||||
<Route path="/" element={<LandingPage />} />
|
||||
<Route path="/feed" element={<MainFeed />} />
|
||||
<Route path="/reviews" element={<ReviewsPage />} />
|
||||
<Route path="/chats" element={<ChatListPage />} />
|
||||
<Route path="/chats/new" element={<ChatPage />} />
|
||||
<Route path="/chats/:chatId" element={<ChatPage />} />
|
||||
<Route path="/chats" element={<ChatsRoute />} />
|
||||
<Route path="/chats/new" element={<ChatsRoute />} />
|
||||
<Route path="/chats/:chatId" element={<ChatsRoute />} />
|
||||
<Route path="/admin/ads" element={<AdminRoute><AdminAdsPage /></AdminRoute>} />
|
||||
<Route path="*" element={<LandingPage />} />
|
||||
</Routes>
|
||||
|
||||
30
src/api/phoneApi.js
Normal file
30
src/api/phoneApi.js
Normal file
@@ -0,0 +1,30 @@
|
||||
// src/api/phoneApi.js
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { apiFetch } from "./apiClient";
|
||||
import { ensureOk } from "./apiErrors";
|
||||
import { solveChallenge } from "../utils/proofOfWork";
|
||||
|
||||
/**
|
||||
* Номер автора объявления. В ленте номера нет: бэкенд отдаёт его только в
|
||||
* обмен на решённую proof-of-work задачу (защита от массового сбора).
|
||||
* Работает и без входа; с токеном лимиты считаются и на аккаунт.
|
||||
*
|
||||
* Бросает ApiError: 404 — номер скрыт или объявление закрыто,
|
||||
* 429 — лимит (Retry-After), 400 — решение не принято.
|
||||
*/
|
||||
export async function revealPhone(postId, { signal } = {}) {
|
||||
const base = `${API_URL}/api/v1/posts/${encodeURIComponent(postId)}/phone`;
|
||||
|
||||
const challengeRes = await ensureOk(await apiFetch(`${base}/challenge`, { signal }));
|
||||
const task = await challengeRes.json();
|
||||
const number = await solveChallenge(task, { signal });
|
||||
|
||||
const res = await ensureOk(await apiFetch(base, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ salt: task.salt, number, signature: task.signature }),
|
||||
signal,
|
||||
}));
|
||||
const { phone } = await res.json();
|
||||
return phone;
|
||||
}
|
||||
118
src/components/GuestGuide.test.jsx
Normal file
118
src/components/GuestGuide.test.jsx
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Подсказка гостю «Ты здесь впервые?» и инструкция: появление с задержкой,
|
||||
* закрытие крестиком и смахиванием вверх, запоминание, открытие инструкции.
|
||||
*/
|
||||
import { render, screen, fireEvent, act } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import "../i18n";
|
||||
import i18n from "../i18n";
|
||||
import GuestGuideBanner, { GUIDE_BANNER_KEY } from "./GuestGuideBanner";
|
||||
import GuideModal from "./GuideModal";
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
function showBanner(props = {}) {
|
||||
render(<GuestGuideBanner onOpenGuide={jest.fn()} {...props} />);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1500);
|
||||
});
|
||||
}
|
||||
|
||||
test("подсказка появляется не сразу, а через секунду", () => {
|
||||
render(<GuestGuideBanner onOpenGuide={jest.fn()} />);
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1500);
|
||||
});
|
||||
expect(screen.getByText("Ты здесь впервые?")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Посмотри, как пользоваться приложением/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("крестик закрывает подсказку навсегда", () => {
|
||||
showBanner();
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Скрыть подсказку"));
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(300);
|
||||
});
|
||||
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("закрытая подсказка больше не показывается", () => {
|
||||
localStorage.setItem(GUIDE_BANNER_KEY, "1");
|
||||
showBanner();
|
||||
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
});
|
||||
|
||||
test("смахивание вверх закрывает, короткое движение — нет", () => {
|
||||
showBanner();
|
||||
const banner = screen.getByRole("status");
|
||||
|
||||
// Чуть-чуть потянули — карточка возвращается на место
|
||||
fireEvent.touchStart(banner, { touches: [{ clientY: 100 }] });
|
||||
fireEvent.touchMove(banner, { touches: [{ clientY: 85 }] });
|
||||
fireEvent.touchEnd(banner);
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBeNull();
|
||||
expect(screen.getByText("Ты здесь впервые?")).toBeInTheDocument();
|
||||
|
||||
// Смахнули вверх — закрылась и запомнилась
|
||||
fireEvent.touchStart(banner, { touches: [{ clientY: 100 }] });
|
||||
fireEvent.touchMove(banner, { touches: [{ clientY: 30 }] });
|
||||
fireEvent.touchEnd(banner);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(300);
|
||||
});
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("кнопка открывает инструкцию и убирает подсказку", () => {
|
||||
const onOpenGuide = jest.fn();
|
||||
showBanner({ onOpenGuide });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Как пользоваться" }));
|
||||
|
||||
expect(onOpenGuide).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("инструкция: шаги, безопасность и вход для гостя", () => {
|
||||
const onClose = jest.fn();
|
||||
const onLoginClick = jest.fn();
|
||||
render(<GuideModal onClose={onClose} onLoginClick={onLoginClick} />);
|
||||
|
||||
expect(screen.getByRole("dialog", { name: "Как пользоваться Находкой" })).toBeInTheDocument();
|
||||
// 6 шагов + 4 совета по безопасности
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(6 + 4);
|
||||
expect(screen.getByText("Ищи в ленте или на карте")).toBeInTheDocument();
|
||||
expect(screen.getByText("Смотри на карте")).toBeInTheDocument();
|
||||
expect(screen.getByText("Пиши автору")).toBeInTheDocument();
|
||||
expect(screen.getByText("Будь осторожен", { exact: false })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Войти или зарегистрироваться" }));
|
||||
expect(onLoginClick).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("инструкция для вошедшего — без кнопки входа", () => {
|
||||
render(<GuideModal onClose={jest.fn()} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Войти или зарегистрироваться" })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Понятно" })).toBeInTheDocument();
|
||||
});
|
||||
124
src/components/GuestGuideBanner.jsx
Normal file
124
src/components/GuestGuideBanner.jsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import "../styles/guide.css";
|
||||
|
||||
export const GUIDE_BANNER_KEY = "nakhodka:guideBannerDismissed";
|
||||
/** Подсказка появляется не сразу: сначала человек видит ленту. */
|
||||
const SHOW_DELAY_MS = 1200;
|
||||
/** Насколько смахнуть вверх, чтобы карточка закрылась, px. */
|
||||
const SWIPE_DISMISS_PX = 40;
|
||||
const LEAVE_ANIMATION_MS = 250;
|
||||
|
||||
export function isGuideBannerDismissed() {
|
||||
try {
|
||||
return localStorage.getItem(GUIDE_BANNER_KEY) === "1";
|
||||
} catch {
|
||||
return false; // приватный режим — просто покажем ещё раз
|
||||
}
|
||||
}
|
||||
|
||||
function rememberDismissed() {
|
||||
try {
|
||||
localStorage.setItem(GUIDE_BANNER_KEY, "1");
|
||||
} catch {
|
||||
// нет хранилища — подсказка вернётся при следующем визите, это не страшно
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ненавязчивая подсказка для гостя в ленте: «Ты здесь впервые?» с кнопкой
|
||||
* инструкции. На телефоне смахивается вверх, на десктопе закрывается крестиком
|
||||
* (крестик есть и на телефоне — смахивание доступно не всем). Закрытая или
|
||||
* открытая один раз подсказка больше не показывается.
|
||||
*
|
||||
* @param {{ onOpenGuide: () => void }} props
|
||||
*/
|
||||
export default function GuestGuideBanner({ onOpenGuide }) {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
const [drag, setDrag] = useState(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const startYRef = useRef(null);
|
||||
const leaveTimerRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isGuideBannerDismissed()) return undefined;
|
||||
const timer = setTimeout(() => setVisible(true), SHOW_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => clearTimeout(leaveTimerRef.current), []);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
rememberDismissed();
|
||||
setLeaving(true);
|
||||
leaveTimerRef.current = setTimeout(() => setVisible(false), LEAVE_ANIMATION_MS);
|
||||
}, []);
|
||||
|
||||
const openGuide = () => {
|
||||
rememberDismissed();
|
||||
setVisible(false);
|
||||
onOpenGuide();
|
||||
};
|
||||
|
||||
const onTouchStart = (e) => {
|
||||
startYRef.current = e.touches[0].clientY;
|
||||
setDragging(true);
|
||||
};
|
||||
|
||||
const onTouchMove = (e) => {
|
||||
if (startYRef.current == null) return;
|
||||
const dy = e.touches[0].clientY - startYRef.current;
|
||||
// Вверх — тянется за пальцем, вниз — едва поддаётся (как у системных уведомлений)
|
||||
setDrag(dy < 0 ? dy : dy / 6);
|
||||
};
|
||||
|
||||
const onTouchEnd = () => {
|
||||
const shouldDismiss = drag < -SWIPE_DISMISS_PX;
|
||||
startYRef.current = null;
|
||||
setDragging(false);
|
||||
if (shouldDismiss) {
|
||||
dismiss();
|
||||
} else {
|
||||
setDrag(0);
|
||||
}
|
||||
};
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const className = [
|
||||
"guest-banner",
|
||||
dragging ? "is-dragging" : "is-settling",
|
||||
leaving ? "is-leaving" : "",
|
||||
].join(" ");
|
||||
|
||||
return (
|
||||
<div
|
||||
className={className}
|
||||
role="status"
|
||||
style={{ "--banner-drag": `${drag}px` }}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
onTouchCancel={onTouchEnd}
|
||||
>
|
||||
<span className="guest-banner-icon" aria-hidden="true">
|
||||
<span className="guest-banner-wave">👋</span>
|
||||
</span>
|
||||
<div className="guest-banner-body">
|
||||
<div className="guest-banner-title">{t("guide.bannerTitle")}</div>
|
||||
<div className="guest-banner-text">{t("guide.bannerText")}</div>
|
||||
<button type="button" className="guest-banner-btn" onClick={openGuide}>
|
||||
{t("guide.bannerButton")}
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="guest-banner-close" onClick={dismiss}
|
||||
aria-label={t("guide.bannerClose")} title={t("guide.bannerClose")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<span className="guest-banner-handle" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
src/components/GuideModal.jsx
Normal file
86
src/components/GuideModal.jsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import "../styles/guide.css";
|
||||
|
||||
const STEPS = [
|
||||
{ key: "search", icon: "🔎" },
|
||||
{ key: "map", icon: "🗺️" },
|
||||
{ key: "create", icon: "📝" },
|
||||
{ key: "chat", icon: "💬" },
|
||||
{ key: "phone", icon: "📞" },
|
||||
{ key: "done", icon: "✅" },
|
||||
];
|
||||
|
||||
const SAFETY = ["safety1", "safety2", "safety3", "safety4"];
|
||||
|
||||
/**
|
||||
* Короткая инструкция для обычного пользователя: шесть шагов и правила
|
||||
* безопасности. Открывается из приветственной подсказки в ленте и из меню.
|
||||
* onLoginClick — для гостя: кнопка «Войти или зарегистрироваться».
|
||||
*
|
||||
* @param {{ onClose: () => void, onLoginClick?: () => void }} props
|
||||
*/
|
||||
export default function GuideModal({ onClose, onLoginClick }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
const onKey = (e) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
document.body.style.overflow = prev;
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<div className="f-modal-bg" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div className="f-modal guide-modal" role="dialog" aria-modal="true" aria-labelledby="guide-title">
|
||||
<div className="f-modal-head">
|
||||
<span className="f-modal-title" id="guide-title">{t("guide.title")}</span>
|
||||
<button type="button" className="f-close-btn" onClick={onClose} aria-label={t("common.close")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="guide-intro">{t("guide.intro")}</p>
|
||||
|
||||
<ol className="guide-steps">
|
||||
{STEPS.map(({ key, icon }, i) => (
|
||||
<li key={key} className="guide-step">
|
||||
<span className="guide-step-icon" aria-hidden="true">{icon}</span>
|
||||
<div className="guide-step-body">
|
||||
<div className="guide-step-title">
|
||||
<span className="guide-step-num">{i + 1}.</span> {t(`guide.${key}Title`)}
|
||||
</div>
|
||||
<div className="guide-step-text">{t(`guide.${key}Text`)}</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
<section className="guide-safety" aria-labelledby="guide-safety-title">
|
||||
<div className="guide-safety-title" id="guide-safety-title">⚠️ {t("guide.safetyTitle")}</div>
|
||||
<ul>
|
||||
{SAFETY.map((key) => <li key={key}>{t(`guide.${key}`)}</li>)}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<div className="guide-actions">
|
||||
{onLoginClick && (
|
||||
<button type="button" className="guide-btn guide-btn-primary" onClick={onLoginClick}>
|
||||
{t("guide.login")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={`guide-btn${onLoginClick ? "" : " guide-btn-primary"}`} onClick={onClose}>
|
||||
{t("guide.gotIt")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,13 +11,13 @@ const MARKER_COLORS = {
|
||||
FOUND: "#34c759",
|
||||
};
|
||||
|
||||
function createMarkerLayout(color, imageUrl) {
|
||||
function createMarkerLayout(color, imageUrl, pinId) {
|
||||
const bgStyle = imageUrl
|
||||
? `background-image:url('${escapeCssUrl(imageUrl)}');background-size:cover;background-position:center;`
|
||||
: "";
|
||||
|
||||
return window.ymaps.templateLayoutFactory.createClass(
|
||||
`<div style="
|
||||
`<div class="f-map-pin" data-pin-id="${escapeHtml(pinId ?? "")}" style="
|
||||
width:40px;height:40px;
|
||||
border-radius:50%;
|
||||
border:3px solid ${color};
|
||||
@@ -86,7 +86,7 @@ function createPostPlacemark(m) {
|
||||
const color = MARKER_COLORS[m.type] || MARKER_COLORS.LOST;
|
||||
const typeLabel = m.type === "FOUND" ? "Находка" : "Потеря";
|
||||
const imgSrc = m.imageUrl ? getImageUrl(m.imageUrl) : null;
|
||||
const iconLayout = createMarkerLayout(color, imgSrc);
|
||||
const iconLayout = createMarkerLayout(color, imgSrc, m.id != null ? String(m.id) : "");
|
||||
|
||||
return new window.ymaps.Placemark(
|
||||
[m.latitude, m.longitude],
|
||||
@@ -111,6 +111,15 @@ function createPostPlacemark(m) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* focusPostId?: any, focusLat?: number, focusLng?: number,
|
||||
* type?: string | null, category?: string | null,
|
||||
* onPostClick?: (id: any) => void, onBack?: () => void,
|
||||
* onMarkersChange?: (markers: any[]) => void, onMarkerHover?: (id: string | null) => void,
|
||||
* highlightId?: string | null, focusTarget?: { lat: number, lng: number, zoom?: number } | null,
|
||||
* }} props
|
||||
*/
|
||||
export default function MapView({
|
||||
focusPostId,
|
||||
focusLat,
|
||||
@@ -119,6 +128,14 @@ export default function MapView({
|
||||
category = null,
|
||||
onPostClick,
|
||||
onBack,
|
||||
// Необязательные пропсы десктопной карты (на мобильном не передаются):
|
||||
// onMarkersChange — список меток в видимой области после каждой загрузки,
|
||||
// onMarkerHover — наведение на метку (id | null), highlightId — подсветка
|
||||
// метки, focusTarget — {lat, lng, zoom?} плавный перелёт к точке.
|
||||
onMarkersChange,
|
||||
onMarkerHover,
|
||||
highlightId = null,
|
||||
focusTarget = null,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// tRef нужен, чтобы читать перевод из эффектов, не добавляя t в их deps:
|
||||
@@ -137,6 +154,11 @@ export default function MapView({
|
||||
|
||||
const onPostClickRef = useRef(onPostClick);
|
||||
onPostClickRef.current = onPostClick;
|
||||
const onMarkersChangeRef = useRef(onMarkersChange);
|
||||
onMarkersChangeRef.current = onMarkersChange;
|
||||
const onMarkerHoverRef = useRef(onMarkerHover);
|
||||
onMarkerHoverRef.current = onMarkerHover;
|
||||
const placemarksRef = useRef(new Map());
|
||||
|
||||
// Фильтры читаются через ref: их смена не должна пересоздавать карту,
|
||||
// они просто уезжают вместе с границами в том же самом запросе.
|
||||
@@ -161,6 +183,7 @@ export default function MapView({
|
||||
if (!collection) return placemarksById;
|
||||
|
||||
collection.removeAll();
|
||||
placemarksRef.current = new Map();
|
||||
|
||||
markers.forEach((m) => {
|
||||
if (m.latitude == null || m.longitude == null) return;
|
||||
@@ -171,14 +194,18 @@ export default function MapView({
|
||||
if (m.id != null) {
|
||||
const postId = String(m.id);
|
||||
placemarksById.set(postId, [m.latitude, m.longitude]);
|
||||
placemarksRef.current.set(postId, placemark);
|
||||
placemark.events.add("click", () => {
|
||||
if (onPostClickRef.current) {
|
||||
onPostClickRef.current(postId);
|
||||
}
|
||||
});
|
||||
placemark.events.add("mouseenter", () => onMarkerHoverRef.current?.(postId));
|
||||
placemark.events.add("mouseleave", () => onMarkerHoverRef.current?.(null));
|
||||
}
|
||||
});
|
||||
|
||||
onMarkersChangeRef.current?.(markers.filter((m) => m.latitude != null && m.longitude != null));
|
||||
return placemarksById;
|
||||
};
|
||||
renderMarkersRef.current = renderMarkers;
|
||||
@@ -362,8 +389,11 @@ export default function MapView({
|
||||
|
||||
// Смена фильтров type/category: догружаем маркеры для текущих границ,
|
||||
// карту при этом не пересоздаём.
|
||||
const prevFiltersRef = useRef({ type, category });
|
||||
useEffect(() => {
|
||||
if (type == null && category == null) return;
|
||||
const prev = prevFiltersRef.current;
|
||||
prevFiltersRef.current = { type, category };
|
||||
if (prev.type === type && prev.category === category) return;
|
||||
const map = ymapRef.current;
|
||||
if (!map) return;
|
||||
const bounds = map.getBounds();
|
||||
@@ -380,6 +410,31 @@ export default function MapView({
|
||||
return () => clearTimeout(timer);
|
||||
}, [type, category]);
|
||||
|
||||
// Подсветка метки (наведение на карточку в списке десктопной карты):
|
||||
// класс на DOM-узле лейаута + zIndex, чтобы метка была поверх соседних.
|
||||
useEffect(() => {
|
||||
if (highlightId == null) return undefined;
|
||||
const id = String(highlightId);
|
||||
const placemark = placemarksRef.current.get(id);
|
||||
placemark?.options.set("zIndex", 1000);
|
||||
const node = mapRef.current?.querySelector(`[data-pin-id="${CSS.escape(id)}"]`);
|
||||
node?.classList.add("is-hl");
|
||||
return () => {
|
||||
placemark?.options.unset("zIndex");
|
||||
node?.classList.remove("is-hl");
|
||||
};
|
||||
}, [highlightId]);
|
||||
|
||||
// Программный перелёт к точке (клик по карточке в списке десктопной карты).
|
||||
useEffect(() => {
|
||||
if (!focusTarget) return;
|
||||
const map = ymapRef.current;
|
||||
if (!map) return;
|
||||
const { lat, lng, zoom } = focusTarget;
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
|
||||
map.setCenter([lat, lng], Math.max(map.getZoom(), zoom ?? FOCUS_ZOOM - 1), { duration: 300 });
|
||||
}, [focusTarget]);
|
||||
|
||||
// Геолокация: если юзер разрешил и карта уже создана — центр на его месте.
|
||||
// Не трогаем, если карта была открыта с фокусом на конкретном объявлении.
|
||||
const hasFocus = focusPostId != null || (Number.isFinite(focusLat) && Number.isFinite(focusLng));
|
||||
|
||||
@@ -237,3 +237,24 @@ test("даже если границы так и не пришли, карта
|
||||
{ timeout: 8000 }
|
||||
);
|
||||
});
|
||||
|
||||
test("в шаблон маркера попадает рабочий URL картинки объявления", async () => {
|
||||
// Регрессия: escapeCssUrl кодировал каждую букву s, и https:// превращался
|
||||
// в http%73:// — кружки рисовались, а фото внутри них пропадали.
|
||||
const imageUrl = "https://s3.example.com/refound/posts/a.jpg?X-Amz-Signature=abc";
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [
|
||||
{ id: 1, latitude: 55.75, longitude: 37.61, type: "FOUND", title: "Ключи", imageUrl },
|
||||
],
|
||||
});
|
||||
const ymaps = installFakeYmaps();
|
||||
|
||||
render(<MapView onBack={() => {}} />);
|
||||
ymaps.publishBounds();
|
||||
|
||||
await waitFor(() => expect(window.ymaps.Placemark).toHaveBeenCalled());
|
||||
|
||||
const template = window.ymaps.templateLayoutFactory.createClass.mock.calls[0][0];
|
||||
expect(template).toContain(`background-image:url('${imageUrl}')`);
|
||||
});
|
||||
|
||||
@@ -6,7 +6,25 @@ import { useAuthContext } from "../context/AuthContext";
|
||||
import PostOnFeed from "../pages/PostOnFeed";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
|
||||
export default function PostDetailModal({ postId, onClose, onLocationClick, onAuthRequired }) {
|
||||
/**
|
||||
* Модалка с полным объявлением, догружаемым по id.
|
||||
*
|
||||
* compact — компактная карточка (без адреса и даты), как при открытии с карты;
|
||||
* hideContact — без кнопки «Написать» (модалка открыта из самого чата);
|
||||
* fallbackTitle — что показать над сообщением, если объявление удалено или скрыто;
|
||||
* footer(post) — дополнительные действия под карточкой.
|
||||
*
|
||||
* @param {{
|
||||
* postId: any, onClose: () => void,
|
||||
* onLocationClick?: (ad: any) => void, onAuthRequired?: () => void,
|
||||
* compact?: boolean, hideContact?: boolean,
|
||||
* fallbackTitle?: string, footer?: (post: any) => any,
|
||||
* }} props
|
||||
*/
|
||||
export default function PostDetailModal({
|
||||
postId, onClose, onLocationClick, onAuthRequired,
|
||||
compact = true, hideContact = false, fallbackTitle, footer,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useAuthContext();
|
||||
const [post, setPost] = useState(null);
|
||||
@@ -21,7 +39,9 @@ export default function PostDetailModal({ postId, onClose, onLocationClick, onAu
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/detail/${postId}`);
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/${encodeURIComponent(postId)}`);
|
||||
// 404 — объявление удалено или снято с публикации (модерация, отклонено)
|
||||
if (res.status === 404) throw new Error("notFound");
|
||||
if (!res.ok) throw new Error("Failed to load post");
|
||||
const data = await res.json();
|
||||
if (!cancelled) {
|
||||
@@ -52,20 +72,31 @@ export default function PostDetailModal({ postId, onClose, onLocationClick, onAu
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
{error === "notFound" && (
|
||||
<div className="f-post-detail-status f-post-detail-gone" role="status">
|
||||
{fallbackTitle && <div className="f-post-detail-gone-title">{fallbackTitle}</div>}
|
||||
<div className="f-post-detail-gone-text">{t("chat.postUnavailable")}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && error !== "notFound" && (
|
||||
<div className="f-post-detail-status f-post-detail-error">
|
||||
{t("common.error")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{post && (
|
||||
<PostOnFeed
|
||||
ad={post}
|
||||
isOwner={isOwner}
|
||||
onLocationClick={onLocationClick}
|
||||
onAuthRequired={onAuthRequired}
|
||||
compact
|
||||
/>
|
||||
<>
|
||||
<PostOnFeed
|
||||
ad={post}
|
||||
isOwner={isOwner}
|
||||
onLocationClick={onLocationClick}
|
||||
onAuthRequired={onAuthRequired}
|
||||
compact={compact}
|
||||
hideContact={hideContact}
|
||||
/>
|
||||
{footer?.(post)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,90 +1,160 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ProfileAvatar from "./profile/ProfileAvatar";
|
||||
import SupportModal from "./SupportModal";
|
||||
import { DesktopIcons } from "./desktop/DesktopIcons";
|
||||
import { getImageUrl } from "../config/authConstants";
|
||||
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
||||
import { formatRelativeTime } from "../utils/relativeTime";
|
||||
|
||||
function FollowButton() {
|
||||
const [following, setFollowing] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<button className="f-right-action-btn" onClick={() => setFollowing(f => !f)}>
|
||||
{following ? t('rightSidebar.following') : t('rightSidebar.subscribe')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const FRESH_LIMIT = 5;
|
||||
|
||||
export default function RightSidebar({ ads, profileData, isAuthenticated, onProfileClick, onLoginClick, onNavClick }) {
|
||||
const { t } = useTranslation();
|
||||
/**
|
||||
* RightSidebar — правая колонка десктопной ленты (>= 1280px, ниже скрыта CSS):
|
||||
* карточка профиля, CTA размещения, переход на карту и свежие объявления.
|
||||
* На мобильной раскладке не отображается.
|
||||
*
|
||||
* @param {{
|
||||
* ads: any[], profileData: any, isAuthenticated: boolean,
|
||||
* onProfileClick: () => void, onLoginClick: () => void, onNavClick?: (key: string) => void,
|
||||
* onCreatePost?: () => void, onMapClick?: () => void, onPostClick?: (id: any) => void,
|
||||
* onRulesClick?: () => void, onReviewsClick?: () => void,
|
||||
* }} props
|
||||
*/
|
||||
export default function RightSidebar({
|
||||
ads,
|
||||
profileData,
|
||||
isAuthenticated,
|
||||
onProfileClick,
|
||||
onLoginClick,
|
||||
onNavClick,
|
||||
onCreatePost,
|
||||
onMapClick,
|
||||
onPostClick,
|
||||
onRulesClick,
|
||||
onReviewsClick,
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [supportOpen, setSupportOpen] = useState(false);
|
||||
|
||||
const suggestions = [...(ads || [])]
|
||||
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
|
||||
.slice(0, 4);
|
||||
// Свежие активные объявления: по дате создания, найденные не показываем.
|
||||
const fresh = useMemo(() => (
|
||||
[...(ads || [])]
|
||||
.filter((ad) => ad.status !== POST_STATUS_CLOSED)
|
||||
.sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0))
|
||||
.slice(0, FRESH_LIMIT)
|
||||
), [ads]);
|
||||
|
||||
const profileName = isAuthenticated
|
||||
? `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim() || profileData?.login
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="f-right">
|
||||
<div className="f-right-profile">
|
||||
<aside className="f-right fd-right">
|
||||
{/* Профиль / гость */}
|
||||
<section className="fd-card fd-profile-card">
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<button type="button" className="fd-profile-row" onClick={onProfileClick}>
|
||||
<ProfileAvatar avatar={profileData?.avatar} name={profileName} />
|
||||
<div className="f-right-profile-info">
|
||||
<div className="f-right-profile-name">{profileName}</div>
|
||||
<div className="f-right-profile-sub">{profileData?.login}</div>
|
||||
</div>
|
||||
<button className="f-right-action-btn" onClick={onProfileClick}>
|
||||
{t('rightSidebar.yourProfile')}
|
||||
</button>
|
||||
</>
|
||||
<span className="fd-profile-info">
|
||||
<span className="fd-profile-name">{profileName}</span>
|
||||
<span className="fd-profile-sub">@{profileData?.login}</span>
|
||||
</span>
|
||||
<DesktopIcons.ChevronRight size={18} />
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<div className="f-ig-ring">
|
||||
<div className="f-ig-avatar">👤</div>
|
||||
<div className="fd-guest">
|
||||
<div className="fd-guest-icon"><DesktopIcons.User size={22} /></div>
|
||||
<div className="fd-guest-text">
|
||||
<div className="fd-guest-title">{t("desktop.guestTitle")}</div>
|
||||
<div className="fd-guest-sub">{t("desktop.guestText")}</div>
|
||||
</div>
|
||||
<div className="f-right-profile-info">
|
||||
<div className="f-right-profile-name">{t('rightSidebar.guest')}</div>
|
||||
<div className="f-right-profile-sub">{t('rightSidebar.guestSub')}</div>
|
||||
</div>
|
||||
<button className="f-right-action-btn" onClick={onLoginClick}>
|
||||
{t('feed.login')}
|
||||
<button type="button" className="fd-btn fd-btn-primary fd-btn-block" onClick={onLoginClick}>
|
||||
{t("feed.login")}
|
||||
</button>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="f-right-header">
|
||||
<span className="f-right-label">{t('rightSidebar.suggestions')}</span>
|
||||
<button className="f-right-link" onClick={() => onNavClick?.("home")}>
|
||||
{t('rightSidebar.all')}
|
||||
{/* CTA размещения */}
|
||||
<section className="fd-card fd-cta-card">
|
||||
<div className="fd-cta-glow" aria-hidden="true" />
|
||||
<div className="fd-cta-icon"><DesktopIcons.Sparkles size={20} /></div>
|
||||
<div className="fd-cta-title">{t("desktop.ctaTitle")}</div>
|
||||
<div className="fd-cta-text">{t("desktop.ctaText")}</div>
|
||||
<button type="button" className="fd-btn fd-btn-brand fd-btn-block fd-cta-btn" onClick={onCreatePost}>
|
||||
<DesktopIcons.Plus size={18} />
|
||||
<span className="fd-cta-btn-label">{t("desktop.createPost")}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{suggestions.length === 0 && (
|
||||
<div className="f-right-suggest-sub">{t('rightSidebar.empty')}</div>
|
||||
)}
|
||||
{/* Карта */}
|
||||
<button type="button" className="fd-card fd-map-card" onClick={onMapClick}>
|
||||
<span className="fd-map-art" aria-hidden="true">
|
||||
<span className="fd-map-road fd-map-road-1" />
|
||||
<span className="fd-map-road fd-map-road-2" />
|
||||
<span className="fd-map-road fd-map-road-3" />
|
||||
<span className="fd-map-pin fd-map-pin-loss" style={{ left: "22%", top: "38%" }} />
|
||||
<span className="fd-map-pin fd-map-pin-found" style={{ left: "58%", top: "24%" }} />
|
||||
<span className="fd-map-pin fd-map-pin-loss" style={{ left: "72%", top: "62%" }} />
|
||||
<span className="fd-map-pin fd-map-pin-found" style={{ left: "36%", top: "70%" }} />
|
||||
</span>
|
||||
<span className="fd-map-body">
|
||||
<span className="fd-map-title">{t("desktop.mapCardTitle")}</span>
|
||||
<span className="fd-map-text">{t("desktop.mapCardText")}</span>
|
||||
<span className="fd-map-link">
|
||||
{t("desktop.mapCardBtn")}
|
||||
<DesktopIcons.ArrowRight size={16} />
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{suggestions.map(ad => (
|
||||
<div className="f-right-suggest" key={ad.id}>
|
||||
<div className="f-ig-ring f-ig-ring-sm">
|
||||
<div className="f-ig-avatar">{ad.emoji || "📋"}</div>
|
||||
</div>
|
||||
<div className="f-right-suggest-info">
|
||||
<div className="f-right-suggest-name">{ad.title}</div>
|
||||
<div className="f-right-suggest-sub">
|
||||
{ad.city || (ad.type === "loss" ? t('postCard.loss') : t('postCard.found'))}
|
||||
</div>
|
||||
</div>
|
||||
<FollowButton />
|
||||
</div>
|
||||
))}
|
||||
{/* Свежие объявления */}
|
||||
<section className="fd-card fd-fresh">
|
||||
<div className="fd-card-head">
|
||||
<span className="fd-card-title">{t("desktop.fresh")}</span>
|
||||
<button type="button" className="fd-link-btn" onClick={() => onNavClick?.("home")}>
|
||||
{t("desktop.seeAll")}
|
||||
</button>
|
||||
</div>
|
||||
{fresh.length === 0 ? (
|
||||
<div className="fd-fresh-empty">{t("desktop.freshEmpty")}</div>
|
||||
) : (
|
||||
<ul className="fd-fresh-list">
|
||||
{fresh.map((ad) => {
|
||||
const img = Array.isArray(ad.images) && ad.images[0] ? getImageUrl(ad.images[0]) : null;
|
||||
const when = formatRelativeTime(ad.createdAt, i18n.language);
|
||||
return (
|
||||
<li key={ad.id}>
|
||||
<button type="button" className="fd-fresh-item" onClick={() => onPostClick?.(ad.id)}>
|
||||
<span className="fd-fresh-thumb">
|
||||
{img ? <img src={img} alt="" loading="lazy" decoding="async" /> : <span>{ad.emoji || "📋"}</span>}
|
||||
<span className={`fd-fresh-type fd-fresh-type-${ad.type === "found" ? "found" : "loss"}`} />
|
||||
</span>
|
||||
<span className="fd-fresh-info">
|
||||
<span className="fd-fresh-title">{ad.title}</span>
|
||||
<span className="fd-fresh-sub">
|
||||
{ad.type === "found" ? t("postCard.found") : t("postCard.loss")}
|
||||
{ad.city && <> · {ad.city}</>}
|
||||
{when && <> · {when}</>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="f-right-foot">
|
||||
<span>© {new Date().getFullYear()} {t('app.name')}</span>
|
||||
<span>{t('rightSidebar.footRules')}</span>
|
||||
<span>{t('rightSidebar.footPrivacy')}</span>
|
||||
<span>{t('rightSidebar.footSupport')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<footer className="fd-right-foot">
|
||||
<button type="button" onClick={onRulesClick}>{t("rightSidebar.footRules")}</button>
|
||||
<button type="button" onClick={onReviewsClick}>{t("nav.reviews")}</button>
|
||||
<button type="button" onClick={() => setSupportOpen(true)}>{t("rightSidebar.footSupport")}</button>
|
||||
<span>© {new Date().getFullYear()} {t("app.name")}</span>
|
||||
</footer>
|
||||
|
||||
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,10 +12,20 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||
import SupportModal from "./SupportModal";
|
||||
import GuideModal from "./GuideModal";
|
||||
import UploadAdModal from "./UploadAdModal";
|
||||
import ProfileAvatar from "./profile/ProfileAvatar";
|
||||
import NahodkaLogo from "./MainNahodkaLogo";
|
||||
import DesktopSidebar from "./desktop/DesktopSidebar";
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* open: boolean, activeNav: string, onClose: () => void, onNavClick: (key: string) => void,
|
||||
* isAuthenticated: boolean, onLoginClick: () => void, onRulesClick?: () => void,
|
||||
* onReviewsClick?: () => void, onCreatePost?: () => void, onProfileClick?: () => void,
|
||||
* onMapClick?: () => void, profileData: any,
|
||||
* }} props
|
||||
*/
|
||||
export default function Sidebar({
|
||||
open,
|
||||
activeNav,
|
||||
@@ -27,6 +37,7 @@ export default function Sidebar({
|
||||
onReviewsClick,
|
||||
onCreatePost,
|
||||
onProfileClick,
|
||||
onMapClick,
|
||||
profileData,
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
@@ -40,7 +51,28 @@ export default function Sidebar({
|
||||
const { language, toggleLanguage } = useLanguageToggle();
|
||||
const [supportOpen, setSupportOpen] = useState(false);
|
||||
const [uploadAdOpen, setUploadAdOpen] = useState(false);
|
||||
const [guideOpen, setGuideOpen] = useState(false);
|
||||
const HelpIcon = NavIcons.help;
|
||||
const BookIcon = NavIcons.book;
|
||||
|
||||
// Десктоп (>= 900px) — отдельная навигация с картой, CTA и свёрткой в рейку.
|
||||
// Мобильный drawer ниже остаётся без изменений.
|
||||
if (isDesktop) {
|
||||
return (
|
||||
<DesktopSidebar
|
||||
activeNav={activeNav}
|
||||
onNavClick={onNavClick}
|
||||
isAuthenticated={isAuthenticated}
|
||||
onLoginClick={onLoginClick}
|
||||
onRulesClick={onRulesClick}
|
||||
onReviewsClick={onReviewsClick || (() => navigate("/reviews"))}
|
||||
onCreatePost={onCreatePost}
|
||||
onProfileClick={onProfileClick}
|
||||
onMapClick={onMapClick}
|
||||
profileData={profileData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const handleNavItem = (itemKey) => {
|
||||
if (!isAuthenticated && itemKey === "myads") {
|
||||
@@ -181,6 +213,16 @@ export default function Sidebar({
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
className="f-sb-item"
|
||||
onClick={() => {
|
||||
setGuideOpen(true);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<BookIcon /> {t('nav.guide')}
|
||||
</button>
|
||||
<button type="button" className="f-sb-item" onClick={() => setSupportOpen(true)}>
|
||||
<HelpIcon /> {t('nav.support')} </button>
|
||||
<div className="f-sb-divider" />
|
||||
@@ -217,6 +259,15 @@ export default function Sidebar({
|
||||
</div>
|
||||
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
|
||||
{uploadAdOpen && <UploadAdModal onClose={() => setUploadAdOpen(false)} />}
|
||||
{guideOpen && (
|
||||
<GuideModal
|
||||
onClose={() => setGuideOpen(false)}
|
||||
onLoginClick={isAuthenticated ? undefined : () => {
|
||||
setGuideOpen(false);
|
||||
onLoginClick();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
100
src/components/chat/AntiFraud.test.jsx
Normal file
100
src/components/chat/AntiFraud.test.jsx
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Антифрод в чате: предупреждения о предоплате и кодах, ответы на контрольные
|
||||
* вопросы находки, решение автора, плашка безопасности и «новый аккаунт».
|
||||
*/
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import i18n from "../../i18n";
|
||||
import MessageBubble from "./MessageBubble";
|
||||
import ClaimForm from "./ClaimForm";
|
||||
import VerificationPanel from "./VerificationPanel";
|
||||
import ChatSafetyNotice, { isNewAccount } from "./ChatSafetyNotice";
|
||||
|
||||
jest.mock("../../api/phoneApi", () => ({ revealPhone: jest.fn() }));
|
||||
|
||||
const t = i18n.t.bind(i18n);
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
const msg = (extra) => ({ id: 1, senderId: 2, content: "Переведите 500 ₽ за доставку", createdAt: "2026-11-10T10:00:00", ...extra });
|
||||
|
||||
test("предупреждение о предоплате видит получатель, а не отправитель", () => {
|
||||
const { rerender } = render(<MessageBubble message={msg({ fraudSignal: "PREPAYMENT" })} isMine={false} />);
|
||||
expect(screen.getByRole("alert").textContent).toMatch(/предоплаты/);
|
||||
|
||||
rerender(<MessageBubble message={msg({ fraudSignal: "PREPAYMENT" })} isMine />);
|
||||
expect(screen.queryByRole("alert")).toBeNull();
|
||||
});
|
||||
|
||||
test("ответы на вопросы показываются карточкой вопрос — ответ", () => {
|
||||
render(<MessageBubble isMine={false} message={msg({
|
||||
kind: "CLAIM",
|
||||
content: "Ответы на вопросы автора находки: ...",
|
||||
claimAnswers: [{ question: "Что на брелке?", answer: "Сова" }],
|
||||
})} />);
|
||||
|
||||
expect(screen.getByText("Ответы на вопросы")).toBeTruthy();
|
||||
expect(screen.getByText("1. Что на брелке?")).toBeTruthy();
|
||||
expect(screen.getByText("Сова")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("решение автора — служебная строка", () => {
|
||||
render(<MessageBubble isMine={false} message={msg({
|
||||
kind: "VERIFICATION", verificationStatus: "APPROVED", content: "Автор находки подтвердил ответы",
|
||||
})} />);
|
||||
|
||||
expect(screen.getByRole("status").className).toContain("chat-system--approved");
|
||||
});
|
||||
|
||||
test("форма ответов отправляется, только когда отвечены все вопросы", () => {
|
||||
const onSubmit = jest.fn();
|
||||
render(<ClaimForm questions={["Что на брелке?", "Цвет чехла?"]} onSubmit={onSubmit} sending={false} t={t} />);
|
||||
const [first, second] = screen.getAllByPlaceholderText("Ваш ответ");
|
||||
const submit = screen.getByText("Отправить ответы");
|
||||
|
||||
fireEvent.change(first, { target: { value: " Сова " } });
|
||||
expect(submit.disabled).toBe(true);
|
||||
fireEvent.change(second, { target: { value: "Синий" } });
|
||||
fireEvent.click(submit);
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledWith(["Сова", "Синий"]);
|
||||
});
|
||||
|
||||
test("автор подтверждает или отклоняет ответы", () => {
|
||||
const onDecide = jest.fn();
|
||||
render(<VerificationPanel status="PENDING" isClaimant={false} onDecide={onDecide} deciding={false} t={t} />);
|
||||
|
||||
fireEvent.click(screen.getByText("Отклонить"));
|
||||
fireEvent.click(screen.getByText("Подтвердить"));
|
||||
expect(onDecide.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
test("заявитель ждёт решения, после подтверждения может открыть номер", () => {
|
||||
const { rerender } = render(<VerificationPanel status="PENDING" isClaimant t={t} />);
|
||||
expect(screen.getByText(/проверяет ваши ответы/)).toBeTruthy();
|
||||
|
||||
rerender(<VerificationPanel status="APPROVED" isClaimant postId={7} phoneVisible t={t} />);
|
||||
expect(screen.getByText("Показать номер автора")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("в обычном чате панели проверки нет", () => {
|
||||
const { container } = render(<VerificationPanel status={null} isClaimant={false} t={t} />);
|
||||
expect(container.innerHTML).toBe("");
|
||||
});
|
||||
|
||||
test("плашку безопасности можно скрыть в чате, отметку о новом аккаунте — нет", () => {
|
||||
const recent = new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString();
|
||||
render(<ChatSafetyNotice chatId={5} otherUserCreatedAt={recent} t={t} />);
|
||||
|
||||
fireEvent.click(screen.getByText("Скрыть"));
|
||||
|
||||
expect(screen.queryByText("Осторожно, мошенники")).toBeNull();
|
||||
expect(screen.getByText(/Новый аккаунт/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("новый аккаунт — моложе недели", () => {
|
||||
const now = Date.parse("2026-11-10T00:00:00Z");
|
||||
expect(isNewAccount("2026-11-05T00:00:00Z", now)).toBe(true);
|
||||
expect(isNewAccount("2026-10-01T00:00:00Z", now)).toBe(false);
|
||||
expect(isNewAccount(null, now)).toBe(false);
|
||||
});
|
||||
@@ -1,14 +1,45 @@
|
||||
export default function ChatHeader({ title, onBack, avatar }) {
|
||||
/**
|
||||
* Шапка чата. С onInfo аватар и заголовок объявления кликабельны, а справа
|
||||
* есть кнопка «ⓘ» — обе открывают карточку объявления, к которому относится чат.
|
||||
*/
|
||||
export default function ChatHeader({ title, onBack, avatar, subtitle, onInfo, infoLabel }) {
|
||||
const main = (
|
||||
<>
|
||||
{avatar !== undefined && (
|
||||
<div className="chat-header-avatar">{avatar}</div>
|
||||
)}
|
||||
<div className="chat-header-text">
|
||||
<div className="chat-header-title">{title}</div>
|
||||
{subtitle}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-header">
|
||||
<button className="chat-back-btn" onClick={onBack}>
|
||||
←
|
||||
</button>
|
||||
{avatar !== undefined && (
|
||||
<div className="chat-header-avatar">{avatar}</div>
|
||||
{onInfo ? (
|
||||
<button type="button" className="chat-header-post" onClick={onInfo} title={infoLabel}>
|
||||
{main}
|
||||
</button>
|
||||
) : (
|
||||
<div className="chat-header-post">{main}</div>
|
||||
)}
|
||||
{onInfo ? (
|
||||
<button type="button" className="chat-header-info-btn" onClick={onInfo}
|
||||
aria-label={infoLabel} title={infoLabel}>
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="12" y1="16" x2="12" y2="11" />
|
||||
<line x1="12" y1="8" x2="12.01" y2="8" />
|
||||
</svg>
|
||||
</button>
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
<div className="chat-header-title">{title}</div>
|
||||
<div />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,130 @@
|
||||
import { ACCEPT } from "../../hooks/useImageUpload";
|
||||
import { formatDuration } from "../../hooks/useVideoAttachment";
|
||||
import CloseIcon from "../icons/CloseIcon";
|
||||
|
||||
// Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде
|
||||
const MAX_MESSAGE_LENGTH = 4000;
|
||||
|
||||
function PaperclipIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
|
||||
strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото или видео
|
||||
* над полем и вставка картинок из буфера обмена. attach: { images, addFiles,
|
||||
* removeImage, fileInputRef, compressing, error, disabled, label, removeLabel,
|
||||
* accept, video, removeVideo, videoProgress }.
|
||||
* notice — блок над полем (статус проверки ответов на вопросы находки);
|
||||
* locked — поля ввода нет, только notice: заявитель ждёт решения автора.
|
||||
*/
|
||||
export default function ChatInputBar({
|
||||
input,
|
||||
onInputChange,
|
||||
onSend,
|
||||
connected,
|
||||
placeholder,
|
||||
attach,
|
||||
sending = false,
|
||||
notice = null,
|
||||
locked = false,
|
||||
}) {
|
||||
const images = attach?.images ?? [];
|
||||
const video = attach?.video ?? null;
|
||||
const progress = attach?.videoProgress;
|
||||
const canSend = connected && !sending && !attach?.compressing && (input.trim() || images.length > 0 || video);
|
||||
|
||||
const handlePaste = (e) => {
|
||||
if (!attach || attach.disabled) return;
|
||||
const files = Array.from(e.clipboardData?.files || []).filter((f) => f.type.startsWith("image/"));
|
||||
if (files.length) {
|
||||
e.preventDefault();
|
||||
attach.addFiles(files);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="chat-input-area">
|
||||
<div className={`chat-input-area${locked ? " chat-input-area--locked" : ""}`}>
|
||||
{notice}
|
||||
{!locked && attach && (images.length > 0 || video || attach.compressing || attach.error) && (
|
||||
<div className="chat-attach-strip">
|
||||
{images.map((img) => (
|
||||
<div key={img.id} className={`chat-attach-thumb${sending ? " is-sending" : ""}`}>
|
||||
<img src={img.preview} alt="" />
|
||||
{!sending && (
|
||||
<button type="button" className="chat-attach-remove"
|
||||
onClick={() => attach.removeImage(img.id)}
|
||||
aria-label={attach.removeLabel} title={attach.removeLabel}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{video && (
|
||||
<div className={`chat-attach-thumb chat-attach-thumb--video${sending ? " is-sending" : ""}`}>
|
||||
<video src={video.preview} muted playsInline preload="metadata" />
|
||||
{video.duration != null && (
|
||||
<span className="chat-attach-duration">{formatDuration(video.duration)}</span>
|
||||
)}
|
||||
{progress != null && (
|
||||
<span className="chat-attach-progress" role="progressbar" aria-valuemin={0} aria-valuemax={100}
|
||||
aria-valuenow={Math.round(progress * 100)}>
|
||||
{Math.round(progress * 100)}%
|
||||
</span>
|
||||
)}
|
||||
{!sending && (
|
||||
<button type="button" className="chat-attach-remove"
|
||||
onClick={attach.removeVideo}
|
||||
aria-label={attach.removeLabel} title={attach.removeLabel}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{attach.compressing && (
|
||||
<div className="chat-attach-thumb chat-attach-thumb--busy"><div className="f-spinner" /></div>
|
||||
)}
|
||||
{attach.error && <div className="chat-attach-error" role="alert">{attach.error}</div>}
|
||||
</div>
|
||||
)}
|
||||
{!locked && (
|
||||
<form onSubmit={onSend} className="chat-input-row">
|
||||
{attach && (
|
||||
<>
|
||||
<button type="button" className="chat-attach-btn"
|
||||
onClick={() => attach.fileInputRef.current?.click()}
|
||||
disabled={attach.disabled || sending}
|
||||
aria-label={attach.label} title={attach.label}>
|
||||
<PaperclipIcon />
|
||||
</button>
|
||||
<input
|
||||
ref={attach.fileInputRef}
|
||||
type="file"
|
||||
accept={attach.accept || ACCEPT}
|
||||
multiple
|
||||
hidden
|
||||
data-testid="chat-attach-input"
|
||||
onChange={(e) => attach.addFiles(e.target.files)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
className="chat-input"
|
||||
maxLength={MAX_MESSAGE_LENGTH}
|
||||
/>
|
||||
<button type="submit" className="chat-send-btn" disabled={!connected}>
|
||||
<button type="submit" className="chat-send-btn" disabled={!canSend} aria-busy={sending}>
|
||||
➤
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getChatDisplayInfo } from "../../utils/chatDisplay";
|
||||
import TrashIcon from "../icons/TrashIcon";
|
||||
import ChatPostMeta from "./ChatPostMeta";
|
||||
|
||||
export default function ChatListItem({ chat, post, unreadMap, t, onOpen, onDelete }) {
|
||||
const { title, imgSrc, emoji, unreadCount, preview } = getChatDisplayInfo(chat, post, unreadMap, t);
|
||||
@@ -18,6 +19,7 @@ export default function ChatListItem({ chat, post, unreadMap, t, onOpen, onDelet
|
||||
</div>
|
||||
<div className="chat-list-info">
|
||||
<div className="chat-list-name">{title}</div>
|
||||
<ChatPostMeta post={post} t={t} />
|
||||
<div className="chat-list-preview">
|
||||
{preview}
|
||||
</div>
|
||||
|
||||
59
src/components/chat/ChatPhotoViewer.jsx
Normal file
59
src/components/chat/ChatPhotoViewer.jsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "../icons/CloseIcon";
|
||||
|
||||
/**
|
||||
* Полноэкранный просмотр фото сообщения: стрелки/точки на десктопе, свайп на
|
||||
* телефоне, Esc и клик по фону — закрыть.
|
||||
*/
|
||||
export default function ChatPhotoViewer({ photos, startIndex = 0, onClose }) {
|
||||
const { t } = useTranslation();
|
||||
const [index, setIndex] = useState(startIndex);
|
||||
const touchStartRef = useRef(null);
|
||||
const count = photos.length;
|
||||
const go = (step) => setIndex((i) => (i + step + count) % count);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
else if (e.key === "ArrowRight" && count > 1) setIndex((i) => (i + 1) % count);
|
||||
else if (e.key === "ArrowLeft" && count > 1) setIndex((i) => (i - 1 + count) % count);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [count, onClose]);
|
||||
|
||||
if (!count) return null;
|
||||
const photo = photos[Math.min(index, count - 1)];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="chat-viewer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onClick={(e) => e.target === e.currentTarget && onClose()}
|
||||
onTouchStart={(e) => { touchStartRef.current = e.touches[0].clientX; }}
|
||||
onTouchEnd={(e) => {
|
||||
const start = touchStartRef.current;
|
||||
touchStartRef.current = null;
|
||||
if (start == null || count < 2) return;
|
||||
const dx = e.changedTouches[0].clientX - start;
|
||||
if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
|
||||
}}
|
||||
>
|
||||
<button type="button" className="chat-viewer-close" onClick={onClose} aria-label={t("common.close")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<img className="chat-viewer-img" src={photo.url} alt="" />
|
||||
{count > 1 && (
|
||||
<>
|
||||
<button type="button" className="chat-viewer-nav chat-viewer-prev" onClick={() => go(-1)}
|
||||
aria-label={t("viewer.prevImage")}>‹</button>
|
||||
<button type="button" className="chat-viewer-nav chat-viewer-next" onClick={() => go(1)}
|
||||
aria-label={t("viewer.nextImage")}>›</button>
|
||||
<div className="chat-viewer-counter">{index + 1} / {count}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
src/components/chat/ChatPhotos.test.jsx
Normal file
86
src/components/chat/ChatPhotos.test.jsx
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Фото в чатах: показ в пузыре и просмотр, отправка сообщения только с фото,
|
||||
* превью «Фото» в списке чатов для сообщения без текста.
|
||||
*/
|
||||
import { createRef } from "react";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import i18n from "../../i18n";
|
||||
import MessageBubble from "./MessageBubble";
|
||||
import ChatInputBar from "./ChatInputBar";
|
||||
import ChatPhotoViewer from "./ChatPhotoViewer";
|
||||
import { getChatDisplayInfo } from "../../utils/chatDisplay";
|
||||
|
||||
const t = i18n.t.bind(i18n);
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
const PHOTOS = [
|
||||
{ id: 1, kind: "PHOTO", url: "https://minio/a.jpg", width: 800, height: 600 },
|
||||
{ id: 2, kind: "PHOTO", url: "https://minio/b.jpg", width: 600, height: 800 },
|
||||
];
|
||||
|
||||
test("фото сообщения показываются и открываются по клику", () => {
|
||||
const onOpenPhoto = jest.fn();
|
||||
const message = { id: 5, content: "", attachments: PHOTOS, createdAt: "2026-10-28T10:00:00" };
|
||||
render(<MessageBubble message={message} isMine onOpenPhoto={onOpenPhoto} />);
|
||||
|
||||
const imgs = screen.getAllByRole("presentation");
|
||||
expect(imgs.map((img) => img.getAttribute("src"))).toEqual(["https://minio/a.jpg", "https://minio/b.jpg"]);
|
||||
|
||||
fireEvent.click(screen.getAllByLabelText("Открыть фото")[1]);
|
||||
expect(onOpenPhoto).toHaveBeenCalledWith(PHOTOS, 1);
|
||||
});
|
||||
|
||||
test("истёкшая ссылка на фото сообщает об ошибке для обновления", () => {
|
||||
const onPhotoError = jest.fn();
|
||||
const message = { id: 5, content: "вот", attachments: [PHOTOS[0]] };
|
||||
render(<MessageBubble message={message} isMine={false} onPhotoError={onPhotoError} />);
|
||||
|
||||
fireEvent.error(screen.getByRole("presentation"));
|
||||
expect(onPhotoError).toHaveBeenCalledWith(message, PHOTOS[0]);
|
||||
expect(screen.getByText("вот")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("сообщение только с фото можно отправить без текста", () => {
|
||||
const attach = {
|
||||
images: [{ id: "img-1", preview: "blob:1" }],
|
||||
addFiles: jest.fn(),
|
||||
removeImage: jest.fn(),
|
||||
fileInputRef: createRef(),
|
||||
compressing: false,
|
||||
error: "",
|
||||
label: "Прикрепить фото",
|
||||
removeLabel: "Убрать фото",
|
||||
};
|
||||
const { rerender } = render(
|
||||
<ChatInputBar input="" onInputChange={() => {}} onSend={() => {}} connected placeholder="" attach={attach} />);
|
||||
|
||||
expect(screen.getByRole("button", { name: "➤" })).toBeEnabled();
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Убрать фото"));
|
||||
expect(attach.removeImage).toHaveBeenCalledWith("img-1");
|
||||
|
||||
rerender(<ChatInputBar input="" onInputChange={() => {}} onSend={() => {}} connected placeholder=""
|
||||
attach={{ ...attach, images: [] }} />);
|
||||
expect(screen.getByRole("button", { name: "➤" })).toBeDisabled();
|
||||
});
|
||||
|
||||
test("просмотр листает фото и закрывается по Esc", () => {
|
||||
const onClose = jest.fn();
|
||||
render(<ChatPhotoViewer photos={PHOTOS} startIndex={0} onClose={onClose} />);
|
||||
|
||||
expect(screen.getByRole("presentation")).toHaveAttribute("src", "https://minio/a.jpg");
|
||||
fireEvent.keyDown(window, { key: "ArrowRight" });
|
||||
expect(screen.getByRole("presentation")).toHaveAttribute("src", "https://minio/b.jpg");
|
||||
expect(screen.getByText("2 / 2")).toBeTruthy();
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("превью в списке чатов: «Фото», если последнее сообщение без текста", () => {
|
||||
const info = getChatDisplayInfo({ id: 1, lastMessage: "", lastMessageAttachments: 2 }, null, {}, t);
|
||||
expect(info.preview).toBe("📷 Фото");
|
||||
const withText = getChatDisplayInfo({ id: 1, lastMessage: "привет", lastMessageAttachments: 1 }, null, {}, t);
|
||||
expect(withText.preview).toBe("привет");
|
||||
});
|
||||
38
src/components/chat/ChatPostInfo.test.jsx
Normal file
38
src/components/chat/ChatPostInfo.test.jsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* По какому объявлению чат: подпись в списке/шапке (тип, город, статус)
|
||||
* и кнопка в шапке, открывающая карточку. Удалённое объявление помечается.
|
||||
*/
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import i18n from "../../i18n";
|
||||
import ChatPostMeta from "./ChatPostMeta";
|
||||
import ChatHeader from "./ChatHeader";
|
||||
import { cachePostsFromChats, getPostForChat } from "../../stores/chatPostStore";
|
||||
|
||||
const t = i18n.t.bind(i18n);
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
test("подпись показывает тип, город и закрытый статус", () => {
|
||||
render(<ChatPostMeta post={{ type: "FOUND", status: "CLOSED", city: "Москва" }} t={t} />);
|
||||
expect(screen.getByText("Находка")).toBeTruthy();
|
||||
expect(screen.getByText("Москва")).toBeTruthy();
|
||||
expect(screen.getByText("Закрыто")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("удалённое объявление сохраняет прежний заголовок и помечается", () => {
|
||||
cachePostsFromChats([{ id: 501, postId: 9, post: { id: 9, title: "Шляпа", images: [] } }]);
|
||||
cachePostsFromChats([{ id: 501, postId: 9, post: null }]);
|
||||
|
||||
const post = getPostForChat(501);
|
||||
expect(post).toMatchObject({ id: 9, title: "Шляпа", removed: true });
|
||||
|
||||
render(<ChatPostMeta post={post} t={t} />);
|
||||
expect(screen.getByText("Объявление удалено")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("кнопка в шапке открывает объявление", () => {
|
||||
const onInfo = jest.fn();
|
||||
render(<ChatHeader title="Шляпа" onBack={() => {}} onInfo={onInfo} infoLabel="Объявление этого чата" />);
|
||||
fireEvent.click(screen.getByLabelText("Объявление этого чата"));
|
||||
expect(onInfo).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
34
src/components/chat/ChatPostMeta.jsx
Normal file
34
src/components/chat/ChatPostMeta.jsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { POST_STATUS_CLOSED } from "../../config/postConstants";
|
||||
|
||||
/**
|
||||
* Короткая подпись объявления, к которому относится чат: тип, город, статус.
|
||||
* Помогает различать чаты по похожим объявлениям (три «шляпы» в списке).
|
||||
* Тип и статус бэкенд отдаёт в верхнем регистре (FOUND, CLOSED).
|
||||
*/
|
||||
export default function ChatPostMeta({ post, t, className = "" }) {
|
||||
if (!post) return null;
|
||||
|
||||
if (post.removed) {
|
||||
return (
|
||||
<div className={`chat-post-meta ${className}`}>
|
||||
<span className="chat-post-tag chat-post-tag--removed">{t("chat.postRemoved")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const type = String(post.type || "").toLowerCase();
|
||||
const isClosed = String(post.status || "").toUpperCase() === POST_STATUS_CLOSED;
|
||||
if (!type && !post.city && !isClosed) return null;
|
||||
|
||||
return (
|
||||
<div className={`chat-post-meta ${className}`}>
|
||||
{type && (
|
||||
<span className={`chat-post-tag chat-post-tag--${type === "found" ? "found" : "loss"}`}>
|
||||
{type === "found" ? t("postCard.found") : t("postCard.loss")}
|
||||
</span>
|
||||
)}
|
||||
{post.city && <span className="chat-post-city">{post.city}</span>}
|
||||
{isClosed && <span className="chat-post-tag chat-post-tag--closed">{t("chat.postClosed")}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
src/components/chat/ChatSafetyNotice.jsx
Normal file
61
src/components/chat/ChatSafetyNotice.jsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useState } from "react";
|
||||
|
||||
const STORAGE_KEY = "nakhodka:safetyNoticeHidden";
|
||||
// Аккаунт моложе недели — частый признак мошенника, который заводит новые под каждую схему
|
||||
const NEW_ACCOUNT_DAYS = 7;
|
||||
|
||||
function readHidden() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Собеседник зарегистрировался меньше недели назад. */
|
||||
export function isNewAccount(createdAt, now = Date.now()) {
|
||||
if (!createdAt) return false;
|
||||
const created = new Date(createdAt).getTime();
|
||||
return Number.isFinite(created) && now - created < NEW_ACCOUNT_DAYS * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Плашка над перепиской: не переводить предоплату, не называть коды. Скрыть
|
||||
* можно в каждом чате отдельно; отметку о новом аккаунте собеседника скрыть
|
||||
* нельзя — она про конкретного человека.
|
||||
*/
|
||||
export default function ChatSafetyNotice({ chatId, otherUserCreatedAt, t }) {
|
||||
const [hidden, setHidden] = useState(() => chatId != null && readHidden().includes(String(chatId)));
|
||||
const newAccount = isNewAccount(otherUserCreatedAt);
|
||||
|
||||
const hide = () => {
|
||||
setHidden(true);
|
||||
if (chatId == null) return;
|
||||
try {
|
||||
const ids = [...new Set([...readHidden(), String(chatId)])].slice(-200);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));
|
||||
} catch {
|
||||
// приватный режим — плашка просто снова появится
|
||||
}
|
||||
};
|
||||
|
||||
if (hidden && !newAccount) return null;
|
||||
|
||||
return (
|
||||
<div className="chat-safety" role="note">
|
||||
{!hidden && (
|
||||
<div className="chat-safety-main">
|
||||
<span className="chat-safety-icon" aria-hidden="true">🛡️</span>
|
||||
<div className="chat-safety-body">
|
||||
<div className="chat-safety-title">{t("chat.safetyTitle")}</div>
|
||||
<div className="chat-safety-text">{t("chat.safetyText")}</div>
|
||||
</div>
|
||||
<button type="button" className="chat-safety-hide" onClick={hide}>
|
||||
{t("chat.safetyHide")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{newAccount && <div className="chat-safety-new">⚠️ {t("chat.newAccount")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
src/components/chat/ChatVideo.test.jsx
Normal file
102
src/components/chat/ChatVideo.test.jsx
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Видео в чатах: состояния в пузыре (обрабатывается / готово / не вышло),
|
||||
* превью выбранного видео с прогрессом загрузки, подпись «Видео» в списке
|
||||
* чатов и проверки файла до отправки.
|
||||
*/
|
||||
import { createRef } from "react";
|
||||
import { render, screen, renderHook, act } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import i18n from "../../i18n";
|
||||
import MessageBubble from "./MessageBubble";
|
||||
import ChatInputBar from "./ChatInputBar";
|
||||
import { getChatDisplayInfo } from "../../utils/chatDisplay";
|
||||
import { formatDuration, useVideoAttachment, MAX_VIDEO_MB } from "../../hooks/useVideoAttachment";
|
||||
|
||||
const t = i18n.t.bind(i18n);
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
const video = (extra) => ({ id: 3, kind: "VIDEO", width: 1280, height: 720, ...extra });
|
||||
|
||||
test("видео в обработке — заглушка без плеера", () => {
|
||||
render(<MessageBubble message={{ id: 1, content: "", attachments: [video({ status: "PROCESSING" })] }} isMine />);
|
||||
|
||||
expect(screen.getByText("Видео обрабатывается…")).toBeInTheDocument();
|
||||
expect(document.querySelector("video")).toBeNull(); // eslint-disable-line testing-library/no-node-access
|
||||
});
|
||||
|
||||
test("готовое видео — плеер с обложкой и длительностью", () => {
|
||||
render(<MessageBubble isMine={false} message={{
|
||||
id: 1, content: "вот", attachments: [video({
|
||||
status: "READY", url: "https://minio/v.mp4", posterUrl: "https://minio/v.jpg", durationMs: 7400,
|
||||
})],
|
||||
}} />);
|
||||
|
||||
// eslint-disable-next-line testing-library/no-node-access
|
||||
const player = document.querySelector("video");
|
||||
expect(player).toHaveAttribute("src", "https://minio/v.mp4");
|
||||
expect(player).toHaveAttribute("poster", "https://minio/v.jpg");
|
||||
expect(screen.getByText("0:07")).toBeInTheDocument();
|
||||
expect(screen.getByText("вот")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("видео не обработалось — понятное сообщение", () => {
|
||||
render(<MessageBubble message={{ id: 1, content: "", attachments: [video({ status: "FAILED" })] }} isMine />);
|
||||
|
||||
expect(screen.getByText("Не удалось обработать видео")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("выбранное видео показывается с длительностью и прогрессом загрузки", () => {
|
||||
const attach = {
|
||||
images: [],
|
||||
video: { file: new File(["x"], "v.mp4", { type: "video/mp4" }), preview: "blob:v", duration: 12.4 },
|
||||
videoProgress: 0.42,
|
||||
addFiles: jest.fn(),
|
||||
removeImage: jest.fn(),
|
||||
removeVideo: jest.fn(),
|
||||
fileInputRef: createRef(),
|
||||
compressing: false,
|
||||
error: "",
|
||||
label: "Прикрепить фото или видео",
|
||||
removeLabel: "Убрать",
|
||||
};
|
||||
render(<ChatInputBar input="" onInputChange={() => {}} onSend={() => {}} connected placeholder=""
|
||||
attach={attach} sending />);
|
||||
|
||||
expect(screen.getByText("0:12")).toBeInTheDocument();
|
||||
expect(screen.getByRole("progressbar")).toHaveTextContent("42%");
|
||||
// Во время отправки видео не убрать
|
||||
expect(screen.queryByLabelText("Убрать")).toBeNull();
|
||||
});
|
||||
|
||||
test("превью в списке чатов: «Видео» для сообщения только с видео", () => {
|
||||
const info = getChatDisplayInfo(
|
||||
{ id: 1, lastMessage: "", lastMessageAttachments: 1, lastMessageAttachmentKind: "VIDEO" }, null, {}, t);
|
||||
expect(info.preview).toBe("🎬 Видео");
|
||||
});
|
||||
|
||||
test("неподходящий формат и слишком большое видео отклоняются до загрузки", async () => {
|
||||
const { result } = renderHook(() => useVideoAttachment());
|
||||
|
||||
let accepted;
|
||||
await act(async () => {
|
||||
accepted = await result.current.selectVideo(new File(["x"], "clip.avi", { type: "video/x-msvideo" }));
|
||||
});
|
||||
expect(accepted).toBe(false);
|
||||
expect(result.current.error).toMatch(/формат/);
|
||||
|
||||
const huge = new File(["x"], "big.mp4", { type: "video/mp4" });
|
||||
Object.defineProperty(huge, "size", { value: (MAX_VIDEO_MB + 1) * 1024 * 1024 });
|
||||
await act(async () => {
|
||||
accepted = await result.current.selectVideo(huge);
|
||||
});
|
||||
expect(accepted).toBe(false);
|
||||
expect(result.current.error).toMatch(/МБ/);
|
||||
expect(result.current.video).toBeNull();
|
||||
});
|
||||
|
||||
test("длительность форматируется как м:сс", () => {
|
||||
expect(formatDuration(7.4)).toBe("0:07");
|
||||
expect(formatDuration(60)).toBe("1:00");
|
||||
expect(formatDuration(null)).toBe("");
|
||||
});
|
||||
45
src/components/chat/ClaimForm.jsx
Normal file
45
src/components/chat/ClaimForm.jsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useState } from "react";
|
||||
|
||||
// Тот же лимит, что ChatClaimService.MAX_ANSWER_LENGTH на бэкенде
|
||||
const MAX_ANSWER_LENGTH = 500;
|
||||
|
||||
/**
|
||||
* Ответы на контрольные вопросы объявления («нашёл», «это моё») вместо первого сообщения.
|
||||
* Чат создаётся вместе с ответами; писать дальше можно после подтверждения.
|
||||
*
|
||||
* @param {{ questions: string[], onSubmit: (answers: string[]) => void, sending: boolean, t: function }} props
|
||||
*/
|
||||
export default function ClaimForm({ questions, onSubmit, sending, t }) {
|
||||
const [answers, setAnswers] = useState(() => questions.map(() => ""));
|
||||
const complete = answers.every((a) => a.trim());
|
||||
|
||||
const submit = (e) => {
|
||||
e.preventDefault();
|
||||
if (!complete || sending) return;
|
||||
onSubmit(answers.map((a) => a.trim()));
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="chat-claim-form" onSubmit={submit}>
|
||||
<div className="chat-claim-title">{t("chat.claimTitle")}</div>
|
||||
<p className="chat-claim-intro">{t("chat.claimIntro")}</p>
|
||||
{questions.map((question, i) => (
|
||||
<label key={i} className="chat-claim-field">
|
||||
<span className="chat-claim-question">{i + 1}. {question}</span>
|
||||
<textarea
|
||||
className="f-m-field chat-claim-answer"
|
||||
rows={2}
|
||||
maxLength={MAX_ANSWER_LENGTH}
|
||||
placeholder={t("chat.claimAnswerPlaceholder")}
|
||||
value={answers[i]}
|
||||
disabled={sending}
|
||||
onChange={(e) => setAnswers((prev) => prev.map((a, j) => (j === i ? e.target.value : a)))}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<button type="submit" className="chat-claim-submit" disabled={!complete || sending}>
|
||||
{sending ? t("chat.claimSending") : t("chat.claimSubmit")}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,125 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatMessageTime } from "../../utils/chatDisplay";
|
||||
import { formatDuration } from "../../hooks/useVideoAttachment";
|
||||
|
||||
export default function MessageBubble({ message, isMine }) {
|
||||
const { i18n } = useTranslation();
|
||||
/** Видео сообщения: пока обрабатывается — заглушка, не обработалось — сообщение об ошибке. */
|
||||
function ChatVideo({ video, onError, t }) {
|
||||
const ratio = video.width && video.height ? `${video.width} / ${video.height}` : "16 / 9";
|
||||
|
||||
if (video.status === "PROCESSING") {
|
||||
return (
|
||||
<div className="chat-video chat-video--pending" style={{ aspectRatio: ratio }} role="status">
|
||||
<div className="f-spinner" />
|
||||
<span>{t("chat.videoProcessing")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (video.status === "FAILED" || !video.url) {
|
||||
return (
|
||||
<div className="chat-video chat-video--failed" style={{ aspectRatio: ratio }} role="status">
|
||||
<span>{t("chat.videoFailed")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="chat-video" style={{ aspectRatio: ratio }}>
|
||||
<video
|
||||
src={video.url}
|
||||
poster={video.posterUrl || undefined}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
onError={onError}
|
||||
/>
|
||||
{video.durationMs != null && (
|
||||
<span className="chat-video-duration">{formatDuration(video.durationMs / 1000)}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Ключи текста предупреждения по FraudSignal с бэкенда
|
||||
const FRAUD_TEXT_KEYS = {
|
||||
PREPAYMENT: "chat.fraudPrepayment",
|
||||
CARD_DATA: "chat.fraudCardData",
|
||||
SMS_CODE: "chat.fraudSmsCode",
|
||||
};
|
||||
|
||||
/**
|
||||
* Пузырь сообщения. Фото (message.attachments) — сеткой над текстом; клик
|
||||
* открывает просмотр. Видео — плеером с обложкой. width/height приходят с
|
||||
* бэкенда: место резервируется сразу, и лента не прыгает, пока файлы грузятся.
|
||||
*/
|
||||
export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoError }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const time = formatMessageTime(message.createdAt, i18n.language);
|
||||
const attachments = Array.isArray(message.attachments) ? message.attachments : [];
|
||||
// Старые ответы бэкенда без kind — это фото
|
||||
const photos = attachments.filter((a) => (a.kind ?? "PHOTO") === "PHOTO");
|
||||
const videos = attachments.filter((a) => a.kind === "VIDEO");
|
||||
const single = photos.length === 1;
|
||||
// Предупреждение — получателю: отправителю незачем подозревать самого себя
|
||||
const fraudKey = !isMine && FRAUD_TEXT_KEYS[message.fraudSignal];
|
||||
const claimAnswers = message.kind === "CLAIM" && Array.isArray(message.claimAnswers)
|
||||
? message.claimAnswers : [];
|
||||
|
||||
// Решение автора по заявке — служебная строка посреди переписки
|
||||
if (message.kind === "VERIFICATION") {
|
||||
return (
|
||||
<div className={`chat-system chat-system--${String(message.verificationStatus || "").toLowerCase()}`}
|
||||
role="status">
|
||||
{message.content}
|
||||
{time && <span className="chat-system-time">{time}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (claimAnswers.length > 0) {
|
||||
return (
|
||||
<div className={`chat-bubble chat-bubble--claim${isMine ? " mine" : ""}`}>
|
||||
<div className="chat-claim-card-title">{t("chat.claimCardTitle")}</div>
|
||||
{claimAnswers.map((qa, i) => (
|
||||
<div key={i} className="chat-claim-qa">
|
||||
<div className="chat-claim-q">{i + 1}. {qa.question}</div>
|
||||
<div className="chat-claim-a">{qa.answer}</div>
|
||||
</div>
|
||||
))}
|
||||
{time && <div className="chat-bubble-time">{time}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`chat-bubble${isMine ? " mine" : ""}`}>
|
||||
{message.content}
|
||||
<div className={`chat-bubble${isMine ? " mine" : ""}${attachments.length ? " has-photos" : ""}`}>
|
||||
{videos.map((video) => (
|
||||
<ChatVideo key={video.id} video={video} t={t} onError={() => onPhotoError?.(message, video)} />
|
||||
))}
|
||||
{photos.length > 0 && (
|
||||
<div className={`chat-photos${single ? " chat-photos--single" : ""}`}>
|
||||
{photos.map((photo, i) => (
|
||||
<button
|
||||
key={photo.id ?? i}
|
||||
type="button"
|
||||
className="chat-photo"
|
||||
style={single && photo.width && photo.height
|
||||
? { aspectRatio: `${photo.width} / ${photo.height}` }
|
||||
: undefined}
|
||||
onClick={() => onOpenPhoto?.(photos, i)}
|
||||
aria-label={t("chat.openPhoto")}
|
||||
>
|
||||
<img
|
||||
src={photo.url}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={() => onPhotoError?.(message, photo)}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{message.content && <div className="chat-bubble-text">{message.content}</div>}
|
||||
{fraudKey && <div className="chat-fraud-warning" role="alert">⚠️ {t(fraudKey)}</div>}
|
||||
{time && <div className="chat-bubble-time">{time}</div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
70
src/components/chat/VerificationPanel.jsx
Normal file
70
src/components/chat/VerificationPanel.jsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import PhoneIcon from "../icons/PhoneIcon";
|
||||
import { useRevealPhone } from "../../hooks/useRevealPhone";
|
||||
import Toast from "../Toast";
|
||||
|
||||
export const VERIFICATION_PENDING = "PENDING";
|
||||
export const VERIFICATION_APPROVED = "APPROVED";
|
||||
export const VERIFICATION_REJECTED = "REJECTED";
|
||||
|
||||
/** Номер автора объявления — заявителю, чьи ответы подтверждены (бэкенд проверяет то же). */
|
||||
function RevealPhone({ postId, t }) {
|
||||
const { phone, loading, error, reveal, clearError } = useRevealPhone(postId);
|
||||
return (
|
||||
<>
|
||||
{phone ? (
|
||||
<a className="chat-verify-phone" href={`tel:${phone}`}><PhoneIcon /> {phone}</a>
|
||||
) : (
|
||||
<button type="button" className="chat-verify-phone" disabled={loading} aria-busy={loading} onClick={reveal}>
|
||||
<PhoneIcon /> {loading ? t("postCard.phoneChecking") : t("chat.revealPhone")}
|
||||
</button>
|
||||
)}
|
||||
{error && <Toast message={error} type="error" onDismiss={clearError} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Состояние заявки к объявлению над полем ввода. Автору — кнопки «Подтвердить» /
|
||||
* «Отклонить»; заявителю — статус проверки, а после подтверждения — номер.
|
||||
* В обычном чате (status == null) ничего не показывает.
|
||||
*/
|
||||
export default function VerificationPanel({ status, isClaimant, postId, phoneVisible, onDecide, deciding, t }) {
|
||||
if (!status) return null;
|
||||
|
||||
if (isClaimant) {
|
||||
if (status === VERIFICATION_APPROVED) {
|
||||
return (
|
||||
<div className="chat-verify chat-verify--approved" role="status">
|
||||
<span>✅ {t("chat.verifyApproved")}</span>
|
||||
{phoneVisible && postId != null && <RevealPhone postId={postId} t={t} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={`chat-verify chat-verify--${status === VERIFICATION_REJECTED ? "rejected" : "pending"}`}
|
||||
role="status">
|
||||
{status === VERIFICATION_REJECTED ? `✖️ ${t("chat.verifyRejected")}` : `⏳ ${t("chat.verifyPending")}`}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === VERIFICATION_APPROVED) return null;
|
||||
const rejected = status === VERIFICATION_REJECTED;
|
||||
return (
|
||||
<div className="chat-verify chat-verify--owner" role="group">
|
||||
<span>{rejected ? t("chat.verifyOwnerRejected") : t("chat.verifyOwnerPrompt")}</span>
|
||||
<div className="chat-verify-actions">
|
||||
{!rejected && (
|
||||
<button type="button" className="chat-verify-btn chat-verify-btn--reject" disabled={deciding}
|
||||
onClick={() => onDecide(false)}>
|
||||
{t("chat.verifyReject")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="chat-verify-btn chat-verify-btn--approve" disabled={deciding}
|
||||
onClick={() => onDecide(true)}>
|
||||
{t("chat.verifyApprove")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
src/components/desktop/DesktopChats.jsx
Normal file
191
src/components/desktop/DesktopChats.jsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Sidebar from "../Sidebar";
|
||||
import ChatListItem from "../chat/ChatListItem";
|
||||
import Toast from "../Toast";
|
||||
import AuthModal from "../AuthModal";
|
||||
import { ProfileModal } from "../profile";
|
||||
import RulesModal from "../../pages/RulesModal";
|
||||
import ChatPage from "../../pages/ChatPage";
|
||||
import { DesktopIcons } from "./DesktopIcons";
|
||||
import { useChatList } from "../../hooks/useChatList";
|
||||
import { useProfileData } from "../../hooks/useProfileData";
|
||||
import { useAuthContext } from "../../context/AuthContext";
|
||||
import { getPostForChat } from "../../stores/chatPostStore";
|
||||
import { getChatDisplayInfo } from "../../utils/chatDisplay";
|
||||
|
||||
/**
|
||||
* DesktopChats — двухпанельный мессенджер десктопа: список чатов слева,
|
||||
* открытая переписка справа. Один компонент обслуживает /chats, /chats/new
|
||||
* и /chats/:chatId, поэтому список не перезагружается при переключении чатов.
|
||||
*/
|
||||
export default function DesktopChats() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { chatId } = useParams();
|
||||
const isDraft = location.pathname === "/chats/new";
|
||||
const { user } = useAuthContext();
|
||||
const profileData = useProfileData(user);
|
||||
const {
|
||||
chats, loading, fetchChats, unreadMap, isAuthenticated,
|
||||
handleDeleteChat, deleteError, clearDeleteError,
|
||||
} = useChatList();
|
||||
const [query, setQuery] = useState("");
|
||||
const [modal, setModal] = useState(null);
|
||||
|
||||
// Новое сообщение в открытом чате → обновляем превью в списке
|
||||
// (с небольшой задержкой, чтобы сервер успел сохранить сообщение).
|
||||
const refreshTimerRef = useRef(null);
|
||||
const refreshList = useCallback(() => {
|
||||
clearTimeout(refreshTimerRef.current);
|
||||
refreshTimerRef.current = setTimeout(() => fetchChats({ silent: true }), 700);
|
||||
}, [fetchChats]);
|
||||
useEffect(() => () => clearTimeout(refreshTimerRef.current), []);
|
||||
|
||||
const items = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return chats
|
||||
.map((chat) => {
|
||||
const post = getPostForChat(chat.id);
|
||||
const info = getChatDisplayInfo(chat, post, unreadMap, t);
|
||||
return { chat, post, info };
|
||||
})
|
||||
.filter(({ info }) => !q
|
||||
|| String(info.title || "").toLowerCase().includes(q)
|
||||
|| String(info.preview || "").toLowerCase().includes(q));
|
||||
}, [chats, unreadMap, query, t]);
|
||||
|
||||
const onDelete = async (id) => {
|
||||
const deleted = await handleDeleteChat(id);
|
||||
if (deleted && String(id) === String(chatId)) navigate("/chats", { replace: true });
|
||||
};
|
||||
|
||||
const goFeed = (state) => navigate("/feed", state ? { state } : undefined);
|
||||
|
||||
return (
|
||||
<div className="f-app fd-chats-app">
|
||||
<Sidebar
|
||||
open={false}
|
||||
activeNav="chat"
|
||||
onClose={() => {}}
|
||||
onNavClick={(key) => goFeed({ desktopNav: key })}
|
||||
isAuthenticated={isAuthenticated}
|
||||
onLoginClick={() => setModal("auth")}
|
||||
onRulesClick={() => setModal("rules")}
|
||||
onReviewsClick={() => navigate("/reviews")}
|
||||
onCreatePost={() => (isAuthenticated ? goFeed({ desktopAction: "create" }) : setModal("auth"))}
|
||||
onProfileClick={() => setModal("profile")}
|
||||
onMapClick={() => navigate("/feed?view=map")}
|
||||
profileData={profileData}
|
||||
/>
|
||||
|
||||
<div className="fd-chats">
|
||||
<section className="fd-chats-list" aria-label={t("chat.chats")}>
|
||||
<div className="fd-chats-list-head">
|
||||
<h1 className="fd-chats-title">
|
||||
{t("chat.chats")}
|
||||
{chats.length > 0 && <span className="fd-chats-count">{chats.length}</span>}
|
||||
</h1>
|
||||
{isAuthenticated && chats.length > 0 && (
|
||||
<label className="fd-chats-search">
|
||||
<DesktopIcons.Search size={17} />
|
||||
<input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("desktop.chats.search")}
|
||||
aria-label={t("desktop.chats.search")}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="fd-chats-scroll">
|
||||
{!isAuthenticated ? (
|
||||
<div className="fd-empty fd-empty-sm">
|
||||
<div className="fd-empty-sub">{t("chat.loginToSee")}</div>
|
||||
</div>
|
||||
) : loading ? (
|
||||
Array.from({ length: 7 }, (_, i) => (
|
||||
<div key={i} className="fd-chat-skeleton" aria-hidden="true">
|
||||
<span className="fd-skeleton fd-chat-skeleton-avatar" />
|
||||
<span className="fd-chat-skeleton-lines">
|
||||
<span className="fd-skeleton fd-skeleton-line" />
|
||||
<span className="fd-skeleton fd-skeleton-line fd-skeleton-line-short" />
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : chats.length === 0 && !isDraft ? (
|
||||
<div className="fd-empty fd-empty-sm">
|
||||
<div className="fd-empty-icon"><DesktopIcons.Message size={24} /></div>
|
||||
<div className="fd-empty-title">{t("chat.noChats")}</div>
|
||||
</div>
|
||||
) : items.length === 0 && !isDraft ? (
|
||||
<div className="fd-empty fd-empty-sm">
|
||||
<div className="fd-empty-sub">{t("desktop.chats.nothingFound")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{isDraft && (
|
||||
<div className="fd-chat-row is-active">
|
||||
<div className="chat-list-item fd-chat-draft">
|
||||
<div className="chat-list-avatar"><DesktopIcons.Plus size={18} /></div>
|
||||
<div className="chat-list-info">
|
||||
<div className="chat-list-name">{location.state?.post?.title || t("desktop.chats.newChat")}</div>
|
||||
<div className="chat-list-preview">{t("desktop.chats.newChat")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{items.map(({ chat, post }) => (
|
||||
<div
|
||||
key={chat.id}
|
||||
className={`fd-chat-row${String(chat.id) === String(chatId) ? " is-active" : ""}`}
|
||||
>
|
||||
<ChatListItem
|
||||
chat={chat}
|
||||
post={post}
|
||||
unreadMap={unreadMap}
|
||||
t={t}
|
||||
onOpen={(id) => navigate(`/chats/${id}`)}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="fd-chats-main">
|
||||
{!isAuthenticated ? (
|
||||
<div className="fd-chats-placeholder">
|
||||
<div className="fd-chats-placeholder-icon"><DesktopIcons.Message size={30} /></div>
|
||||
<div className="fd-empty-title">{t("chat.loginToSee")}</div>
|
||||
<button type="button" className="fd-btn fd-btn-primary" onClick={() => setModal("auth")}>
|
||||
{t("feed.login")}
|
||||
</button>
|
||||
</div>
|
||||
) : chatId || isDraft ? (
|
||||
<ChatPage key={chatId || "new"} embedded onActivity={refreshList} />
|
||||
) : (
|
||||
<div className="fd-chats-placeholder">
|
||||
<div className="fd-chats-placeholder-icon"><DesktopIcons.Message size={30} /></div>
|
||||
<div className="fd-empty-title">{t("desktop.chats.selectTitle")}</div>
|
||||
<div className="fd-empty-sub">{t("desktop.chats.selectSub")}</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{deleteError && <Toast message={deleteError} type="error" onDismiss={clearDeleteError} />}
|
||||
{modal === "auth" && <AuthModal onClose={() => setModal(null)} />}
|
||||
{modal === "rules" && <RulesModal onClose={() => setModal(null)} />}
|
||||
{modal === "profile" && isAuthenticated && (
|
||||
<ProfileModal onClose={() => setModal(null)} initialData={profileData} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
131
src/components/desktop/DesktopFeedHeader.jsx
Normal file
131
src/components/desktop/DesktopFeedHeader.jsx
Normal file
@@ -0,0 +1,131 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FeedSearchBar from "../feed/FeedSearchBar";
|
||||
import CityFilter from "../CityFilter";
|
||||
import { DesktopIcons } from "./DesktopIcons";
|
||||
|
||||
const TITLE_KEYS = {
|
||||
home: "nav.home",
|
||||
items: "nav.items",
|
||||
pets: "nav.pets",
|
||||
myads: "nav.myAds",
|
||||
};
|
||||
|
||||
/**
|
||||
* Сегментированный переключатель «Все / Потери / Находки».
|
||||
* Индикатор активного сегмента — отдельный слой, который едет под кнопками.
|
||||
*/
|
||||
export function TypeSegment({ value, onChange, size = "md" }) {
|
||||
const { t } = useTranslation();
|
||||
const options = [
|
||||
{ key: null, label: t("desktop.typeAll") },
|
||||
{ key: "loss", label: t("feed.filterLoss"), tone: "loss" },
|
||||
{ key: "found", label: t("feed.filterFound"), tone: "found" },
|
||||
];
|
||||
const activeIndex = Math.max(0, options.findIndex((o) => o.key === value));
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`fd-segment fd-segment-${size}`}
|
||||
role="radiogroup"
|
||||
aria-label={String(t("feed.openFilter"))}
|
||||
style={{ "--fd-seg-index": activeIndex, "--fd-seg-count": options.length }}
|
||||
>
|
||||
<span className="fd-segment-thumb" aria-hidden="true" />
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
key={opt.key ?? "all"}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={value === opt.key}
|
||||
className={`fd-segment-btn${value === opt.key ? " is-active" : ""}`}
|
||||
onClick={() => onChange(opt.key)}
|
||||
>
|
||||
{opt.tone && <span className={`fd-dot fd-dot-${opt.tone}`} aria-hidden="true" />}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* DesktopFeedHeader — шапка ленты на десктопе: заголовок раздела, счётчик,
|
||||
* фильтр «потеря/находка», поиск с подсказками и мультивыбор городов.
|
||||
* На мобильном не рендерится (там FeedTopBar + шапка поиска).
|
||||
*/
|
||||
export default function DesktopFeedHeader({
|
||||
activeNav,
|
||||
typeFilter,
|
||||
onTypeFilterChange,
|
||||
searchQuery,
|
||||
onSearchChange,
|
||||
cities,
|
||||
selectedCities,
|
||||
onCitiesChange,
|
||||
count,
|
||||
loading,
|
||||
onMapClick,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const searching = searchQuery.trim().length > 0 || selectedCities.length > 0;
|
||||
const titleKey = TITLE_KEYS[activeNav] || "nav.home";
|
||||
const showSearch = activeNav !== "myads";
|
||||
const hasFilters = searching || typeFilter != null;
|
||||
|
||||
const reset = () => {
|
||||
onSearchChange("");
|
||||
onCitiesChange([]);
|
||||
onTypeFilterChange(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="fd-feed-header">
|
||||
<div className="fd-feed-header-inner">
|
||||
<div className="fd-feed-title-row">
|
||||
<div className="fd-feed-title-block">
|
||||
<h1 className="fd-feed-title">
|
||||
{searching ? t("desktop.searchResults") : t(titleKey)}
|
||||
</h1>
|
||||
<p className="fd-feed-sub">
|
||||
{t(`desktop.feedSub.${TITLE_KEYS[activeNav] ? activeNav : "home"}`)}
|
||||
{!loading && count > 0 && (
|
||||
<>
|
||||
<span className="fd-sep" aria-hidden="true">·</span>
|
||||
<span className="fd-feed-count">{t("desktop.shown", { count })}</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="fd-feed-title-actions">
|
||||
{hasFilters && (
|
||||
<button type="button" className="fd-link-btn" onClick={reset}>
|
||||
<DesktopIcons.Close size={16} />
|
||||
{t("desktop.resetFilters")}
|
||||
</button>
|
||||
)}
|
||||
{onMapClick && (
|
||||
<button type="button" className="fd-ghost-btn" onClick={onMapClick}>
|
||||
<DesktopIcons.Map size={18} />
|
||||
{t("nav.map")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fd-feed-controls">
|
||||
<TypeSegment value={typeFilter} onChange={onTypeFilterChange} />
|
||||
{showSearch && (
|
||||
<div className="fd-feed-search">
|
||||
<FeedSearchBar value={searchQuery} onChange={onSearchChange} t={t} />
|
||||
</div>
|
||||
)}
|
||||
{activeNav === "home" && (
|
||||
<div className="fd-feed-city">
|
||||
<CityFilter cities={cities} value={selectedCities} onChange={onCitiesChange} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
89
src/components/desktop/DesktopIcons.jsx
Normal file
89
src/components/desktop/DesktopIcons.jsx
Normal file
@@ -0,0 +1,89 @@
|
||||
// Линейные иконки десктопной раскладки (единый стиль: 24×24, stroke 2).
|
||||
const base = {
|
||||
viewBox: "0 0 24 24",
|
||||
fill: "none",
|
||||
stroke: "currentColor",
|
||||
strokeWidth: 2,
|
||||
strokeLinecap: "round",
|
||||
strokeLinejoin: "round",
|
||||
"aria-hidden": true,
|
||||
};
|
||||
|
||||
const Svg = ({ size = 20, children, ...rest }) => (
|
||||
<svg width={size} height={size} {...base} {...rest}>{children}</svg>
|
||||
);
|
||||
|
||||
export const DesktopIcons = {
|
||||
Info: (p) => (
|
||||
<Svg {...p}>
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="12" y1="16" x2="12" y2="11" />
|
||||
<line x1="12" y1="8" x2="12.01" y2="8" />
|
||||
</Svg>
|
||||
),
|
||||
Map: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z" />
|
||||
<path d="M15 5.764v15" />
|
||||
<path d="M9 3.236v15" />
|
||||
</Svg>
|
||||
),
|
||||
Plus: (p) => (
|
||||
<Svg strokeWidth={2.4} {...p}>
|
||||
<path d="M12 5v14" />
|
||||
<path d="M5 12h14" />
|
||||
</Svg>
|
||||
),
|
||||
User: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="12" cy="7" r="4" />
|
||||
</Svg>
|
||||
),
|
||||
Pin: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" />
|
||||
<circle cx="12" cy="10" r="3" />
|
||||
</Svg>
|
||||
),
|
||||
ArrowRight: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M5 12h14" />
|
||||
<path d="m12 5 7 7-7 7" />
|
||||
</Svg>
|
||||
),
|
||||
ChevronRight: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="m9 18 6-6-6-6" />
|
||||
</Svg>
|
||||
),
|
||||
Search: (p) => (
|
||||
<Svg {...p}>
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<path d="m21 21-4.3-4.3" />
|
||||
</Svg>
|
||||
),
|
||||
Message: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
|
||||
</Svg>
|
||||
),
|
||||
Close: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M18 6 6 18" />
|
||||
<path d="m6 6 12 12" />
|
||||
</Svg>
|
||||
),
|
||||
Sparkles: (p) => (
|
||||
<Svg {...p}>
|
||||
<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" />
|
||||
</Svg>
|
||||
),
|
||||
Image: (p) => (
|
||||
<Svg {...p}>
|
||||
<rect width="18" height="18" x="3" y="3" rx="2" />
|
||||
<circle cx="9" cy="9" r="2" />
|
||||
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
|
||||
</Svg>
|
||||
),
|
||||
};
|
||||
163
src/components/desktop/DesktopMapView.jsx
Normal file
163
src/components/desktop/DesktopMapView.jsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import MapView from "../MapView";
|
||||
import { TypeSegment } from "./DesktopFeedHeader";
|
||||
import { DesktopIcons } from "./DesktopIcons";
|
||||
import { getImageUrl } from "../../config/authConstants";
|
||||
import { CATEGORIES } from "../../config/feedConstants";
|
||||
|
||||
// Список рендерим ограниченным: в крупном масштабе в область могут попасть
|
||||
// сотни меток, а пользователю всё равно нужен ближайший десяток.
|
||||
const LIST_LIMIT = 150;
|
||||
|
||||
/**
|
||||
* DesktopMapView — карта объявлений для десктопа: слева панель с фильтрами
|
||||
* и списком объявлений из видимой области, справа карта.
|
||||
* Наведение на карточку подсвечивает метку и наоборот; клик по карточке
|
||||
* открывает объявление, кнопка с пином — плавно перелетает к метке.
|
||||
*/
|
||||
export default function DesktopMapView({ focusPostId, focusLat, focusLng, onPostClick }) {
|
||||
const { t } = useTranslation();
|
||||
const [type, setType] = useState(null);
|
||||
const [category, setCategory] = useState(null);
|
||||
const [markers, setMarkers] = useState(null);
|
||||
const [hoverId, setHoverId] = useState(null);
|
||||
const [focusTarget, setFocusTarget] = useState(null);
|
||||
const listRef = useRef(null);
|
||||
|
||||
const handleMarkers = useCallback((list) => setMarkers(list), []);
|
||||
|
||||
// Наведение на метку карты: подсвечиваем карточку и докручиваем к ней список.
|
||||
const handleMarkerHover = useCallback((id) => {
|
||||
setHoverId(id);
|
||||
if (id == null) return;
|
||||
const node = listRef.current?.querySelector(`[data-item-id="${CSS.escape(String(id))}"]`);
|
||||
node?.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
// Открытие с фокусом на объявлении — сразу подсвечиваем его в списке.
|
||||
useEffect(() => {
|
||||
if (focusPostId != null) setHoverId(String(focusPostId));
|
||||
}, [focusPostId]);
|
||||
|
||||
const visible = markers ? markers.slice(0, LIST_LIMIT) : [];
|
||||
|
||||
return (
|
||||
<div className="fd-map">
|
||||
<aside className="fd-map-panel">
|
||||
<div className="fd-map-panel-head">
|
||||
<h1 className="fd-map-title-h">{t("desktop.map.title")}</h1>
|
||||
<TypeSegment value={type} onChange={setType} size="sm" />
|
||||
<div className="fd-chips" role="radiogroup" aria-label={t("post.category")}>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={category == null}
|
||||
className={`fd-chip${category == null ? " is-active" : ""}`}
|
||||
onClick={() => setCategory(null)}
|
||||
>
|
||||
{t("desktop.map.catAll")}
|
||||
</button>
|
||||
{CATEGORIES.map((c) => (
|
||||
<button
|
||||
key={c.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={category === c.value}
|
||||
className={`fd-chip${category === c.value ? " is-active" : ""}`}
|
||||
onClick={() => setCategory(c.value)}
|
||||
>
|
||||
{t(c.labelKey)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="fd-map-count">
|
||||
{markers == null
|
||||
? t("desktop.map.loading")
|
||||
: t("desktop.map.inArea", { count: markers.length })}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="fd-map-list" ref={listRef}>
|
||||
{markers == null && (
|
||||
Array.from({ length: 6 }, (_, i) => (
|
||||
<div key={i} className="fd-map-item fd-skeleton-item" aria-hidden="true">
|
||||
<span className="fd-map-item-thumb fd-skeleton" />
|
||||
<span className="fd-map-item-body">
|
||||
<span className="fd-skeleton fd-skeleton-line" />
|
||||
<span className="fd-skeleton fd-skeleton-line fd-skeleton-line-short" />
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
{markers != null && markers.length === 0 && (
|
||||
<div className="fd-empty fd-empty-sm">
|
||||
<div className="fd-empty-icon"><DesktopIcons.Pin size={26} /></div>
|
||||
<div className="fd-empty-title">{t("desktop.map.emptyArea")}</div>
|
||||
<div className="fd-empty-sub">{t("desktop.map.emptyAreaSub")}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{visible.map((m) => {
|
||||
const id = String(m.id);
|
||||
const img = m.imageUrl ? getImageUrl(m.imageUrl) : null;
|
||||
const isFound = m.type === "FOUND";
|
||||
return (
|
||||
<div
|
||||
key={id}
|
||||
data-item-id={id}
|
||||
className={`fd-map-item${hoverId === id ? " is-hl" : ""}`}
|
||||
onMouseEnter={() => setHoverId(id)}
|
||||
onMouseLeave={() => setHoverId(null)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-map-item-main"
|
||||
onClick={() => onPostClick(id)}
|
||||
title={t("desktop.map.open")}
|
||||
>
|
||||
<span className="fd-map-item-thumb">
|
||||
{img
|
||||
? <img src={img} alt="" loading="lazy" decoding="async" />
|
||||
: <DesktopIcons.Image size={20} />}
|
||||
</span>
|
||||
<span className="fd-map-item-body">
|
||||
<span className="fd-map-item-title">{m.title}</span>
|
||||
<span className={`fd-badge ${isFound ? "fd-badge-found" : "fd-badge-loss"}`}>
|
||||
{isFound ? t("postCard.found") : t("postCard.loss")}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-icon-btn fd-map-item-locate"
|
||||
onClick={() => setFocusTarget({ lat: m.latitude, lng: m.longitude })}
|
||||
title={t("desktop.map.showOnMap")}
|
||||
aria-label={t("desktop.map.showOnMap")}
|
||||
>
|
||||
<DesktopIcons.Pin size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div className="fd-map-canvas">
|
||||
<MapView
|
||||
focusPostId={focusPostId}
|
||||
focusLat={focusLat}
|
||||
focusLng={focusLng}
|
||||
type={type}
|
||||
category={category}
|
||||
onPostClick={onPostClick}
|
||||
onMarkersChange={handleMarkers}
|
||||
onMarkerHover={handleMarkerHover}
|
||||
highlightId={hoverId}
|
||||
focusTarget={focusTarget}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
270
src/components/desktop/DesktopSidebar.jsx
Normal file
270
src/components/desktop/DesktopSidebar.jsx
Normal file
@@ -0,0 +1,270 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { NavIcons } from "../icons/NavIcons";
|
||||
import SunIcon from "../icons/SunIcon";
|
||||
import MoonIcon from "../icons/MoonIcon";
|
||||
import GlobeIcon from "../icons/GlobeIcon";
|
||||
import NahodkaLogo from "../MainNahodkaLogo";
|
||||
import ProfileAvatar from "../profile/ProfileAvatar";
|
||||
import SupportModal from "../SupportModal";
|
||||
import GuideModal from "../GuideModal";
|
||||
import UploadAdModal from "../UploadAdModal";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
import { useUnread } from "../../context/UnreadContext";
|
||||
import { useAuthContext } from "../../context/AuthContext";
|
||||
import { useLanguageToggle } from "../../hooks/useLanguageToggle";
|
||||
import { DesktopIcons } from "./DesktopIcons";
|
||||
|
||||
// Порядок пунктов основной навигации десктопа. «Карта» есть только здесь:
|
||||
// на мобильном она живёт в нижней панели (BottomNav).
|
||||
const MAIN_NAV = [
|
||||
{ key: "home", labelKey: "nav.home", icon: () => NavIcons.grid() },
|
||||
{ key: "items", labelKey: "nav.items", icon: () => NavIcons.box() },
|
||||
{ key: "pets", labelKey: "nav.pets", icon: () => NavIcons.paw() },
|
||||
{ key: "map", labelKey: "nav.map", icon: () => <DesktopIcons.Map /> },
|
||||
{ key: "myads", labelKey: "nav.myAds", icon: () => NavIcons.file() },
|
||||
{ key: "chat", labelKey: "nav.chat", icon: () => NavIcons.chat() },
|
||||
];
|
||||
|
||||
const ADMIN_NAV = [
|
||||
{ key: "admin-campaigns", labelKey: "adminPanel.campaignsNav", icon: () => NavIcons.grid(), to: "/admin/ads" },
|
||||
{ key: "admin-posts", labelKey: "adminPanel.postsNav", icon: () => NavIcons.rules(), to: "/admin/ads?tab=posts" },
|
||||
{ key: "admin-posts-rejected", labelKey: "adminPanel.postsRejectedNav", icon: () => NavIcons.rules(), to: "/admin/ads?tab=rejected" },
|
||||
];
|
||||
|
||||
/**
|
||||
* DesktopSidebar — левая навигация десктопной раскладки (>= 900px).
|
||||
*
|
||||
* На 900–1199px автоматически сворачивается в узкую «рейку» с иконками
|
||||
* (подписи скрываются CSS-ом, остаются title-подсказки), на >= 1200px —
|
||||
* полная панель с подписями. Мобильный drawer — отдельный компонент Sidebar.
|
||||
*/
|
||||
export default function DesktopSidebar({
|
||||
activeNav,
|
||||
onNavClick,
|
||||
isAuthenticated,
|
||||
onLoginClick,
|
||||
onRulesClick,
|
||||
onReviewsClick,
|
||||
onCreatePost,
|
||||
onProfileClick,
|
||||
onMapClick,
|
||||
profileData,
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
const { isAdmin } = useAuthContext();
|
||||
const { theme, toggle: toggleTheme } = useTheme();
|
||||
const { totalUnread } = useUnread();
|
||||
const { language, toggleLanguage } = useLanguageToggle();
|
||||
const [supportOpen, setSupportOpen] = useState(false);
|
||||
const [uploadAdOpen, setUploadAdOpen] = useState(false);
|
||||
const [guideOpen, setGuideOpen] = useState(false);
|
||||
|
||||
const profileName = `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim();
|
||||
|
||||
const handleMain = (key) => {
|
||||
if (key === "chat") {
|
||||
if (!isAuthenticated) onLoginClick();
|
||||
else navigate("/chats");
|
||||
return;
|
||||
}
|
||||
if (key === "myads" && !isAuthenticated) {
|
||||
onLoginClick();
|
||||
return;
|
||||
}
|
||||
if (key === "map") {
|
||||
if (onMapClick) onMapClick();
|
||||
else navigate("/feed?view=map");
|
||||
return;
|
||||
}
|
||||
onNavClick(key);
|
||||
};
|
||||
|
||||
const handleProfile = () => {
|
||||
if (!isAuthenticated) onLoginClick();
|
||||
else onProfileClick?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside className="fd-sidebar" aria-label={t("feed.openMenu")}>
|
||||
<div className="fd-sb-head">
|
||||
{/* На десктопе логотип ведёт во «Все объявления»; лендинг — пункт «О сервисе» внизу */}
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-logo"
|
||||
onClick={() => handleMain("home")}
|
||||
title={t("app.name")}
|
||||
aria-label={t("app.name")}
|
||||
>
|
||||
<NahodkaLogo className="fd-sb-logo-full" />
|
||||
<img src="/favicon.svg" alt="" className="fd-sb-logo-mark" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-cta"
|
||||
onClick={onCreatePost}
|
||||
title={t("desktop.createPost")}
|
||||
>
|
||||
<DesktopIcons.Plus />
|
||||
<span className="fd-sb-label">{t("desktop.createPost")}</span>
|
||||
</button>
|
||||
|
||||
<nav className="fd-sb-nav">
|
||||
{MAIN_NAV.map(({ key, labelKey, icon }) => (
|
||||
<button
|
||||
type="button"
|
||||
key={key}
|
||||
className={`fd-sb-item${activeNav === key ? " is-active" : ""}`}
|
||||
onClick={() => handleMain(key)}
|
||||
title={t(labelKey)}
|
||||
aria-current={activeNav === key ? "page" : undefined}
|
||||
>
|
||||
<span className="fd-sb-icon">
|
||||
{icon()}
|
||||
{key === "chat" && totalUnread > 0 && <span className="fd-sb-dot" />}
|
||||
</span>
|
||||
<span className="fd-sb-label">{t(labelKey)}</span>
|
||||
{key === "chat" && totalUnread > 0 && (
|
||||
<span className="fd-sb-badge">{totalUnread > 99 ? "99+" : totalUnread}</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<div className="fd-sb-section">{t("desktop.adminSection")}</div>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item"
|
||||
onClick={() => setUploadAdOpen(true)}
|
||||
title={t("admin.uploadAd")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.megaphone()}</span>
|
||||
<span className="fd-sb-label">{t("admin.uploadAd")}</span>
|
||||
</button>
|
||||
{ADMIN_NAV.map(({ key, labelKey, icon, to }) => (
|
||||
<button
|
||||
type="button"
|
||||
key={key}
|
||||
className={`fd-sb-item${activeNav === key ? " is-active" : ""}`}
|
||||
onClick={() => navigate(to)}
|
||||
title={t(labelKey)}
|
||||
>
|
||||
<span className="fd-sb-icon">{icon()}</span>
|
||||
<span className="fd-sb-label">{t(labelKey)}</span>
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="fd-sb-bottom">
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
onClick={() => navigate("/")}
|
||||
title={t("nav.about")}
|
||||
>
|
||||
<span className="fd-sb-icon"><DesktopIcons.Info /></span>
|
||||
<span className="fd-sb-label">{t("nav.about")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`fd-sb-item fd-sb-item-sm${activeNav === "reviews" ? " is-active" : ""}`}
|
||||
onClick={onReviewsClick}
|
||||
title={t("nav.reviews")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.star()}</span>
|
||||
<span className="fd-sb-label">{t("nav.reviews")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
onClick={() => setGuideOpen(true)}
|
||||
title={t("nav.guide")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.book()}</span>
|
||||
<span className="fd-sb-label">{t("nav.guide")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
onClick={onRulesClick}
|
||||
title={t("nav.rules")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.rules()}</span>
|
||||
<span className="fd-sb-label">{t("nav.rules")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
onClick={() => setSupportOpen(true)}
|
||||
title={t("nav.support")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.help()}</span>
|
||||
<span className="fd-sb-label">{t("nav.support")}</span>
|
||||
</button>
|
||||
|
||||
<div className="fd-sb-prefs">
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-pref"
|
||||
onClick={toggleTheme}
|
||||
title={theme === "dark" ? t("sidebar.lightTheme") : t("sidebar.darkTheme")}
|
||||
aria-label={theme === "dark" ? t("sidebar.lightTheme") : t("sidebar.darkTheme")}
|
||||
>
|
||||
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-pref fd-sb-pref-lang"
|
||||
onClick={toggleLanguage}
|
||||
title={language === "ru" ? "English" : "Русский"}
|
||||
aria-label={language === "ru" ? "English" : "Русский"}
|
||||
>
|
||||
<GlobeIcon />
|
||||
<span>{language === "ru" ? "RU" : "EN"}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-profile"
|
||||
onClick={handleProfile}
|
||||
title={isAuthenticated ? t("desktop.myProfile") : t("feed.login")}
|
||||
>
|
||||
{isAuthenticated ? (
|
||||
<ProfileAvatar avatar={profileData?.avatar} name={profileName} />
|
||||
) : (
|
||||
<span className="fd-sb-profile-guest"><DesktopIcons.User /></span>
|
||||
)}
|
||||
<span className="fd-sb-profile-info fd-sb-label">
|
||||
<span className="fd-sb-profile-name">
|
||||
{isAuthenticated ? profileName || profileData?.login : t("feed.login")}
|
||||
</span>
|
||||
<span className="fd-sb-profile-sub">
|
||||
{isAuthenticated ? `@${profileData?.login || t("profile.default")}` : t("desktop.guestText")}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
|
||||
{uploadAdOpen && <UploadAdModal onClose={() => setUploadAdOpen(false)} />}
|
||||
{guideOpen && (
|
||||
<GuideModal
|
||||
onClose={() => setGuideOpen(false)}
|
||||
onLoginClick={isAuthenticated ? undefined : () => {
|
||||
setGuideOpen(false);
|
||||
onLoginClick();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -56,6 +56,13 @@ export const NavIcons = {
|
||||
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||
</svg>
|
||||
),
|
||||
// Открытая книга — «Инструкция»
|
||||
book: () => (
|
||||
<svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z" />
|
||||
<path d="M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z" />
|
||||
</svg>
|
||||
),
|
||||
megaphone: () => (
|
||||
<svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="m3 11 18-5v12L3 14v-3z" />
|
||||
|
||||
@@ -24,15 +24,24 @@ function ImageUpload({
|
||||
fileInputRef,
|
||||
onFileChange,
|
||||
onRemove,
|
||||
// Перетаскивание фото (десктоп): обработчики зоны и «файл над зоной».
|
||||
// Пустые props — перетаскивание выключено (мобильная раскладка).
|
||||
dropZoneProps = {},
|
||||
dragOver = false,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const dropEnabled = Object.keys(dropZoneProps).length > 0;
|
||||
|
||||
return (
|
||||
<div className="f-m-group">
|
||||
<div
|
||||
className={`f-m-group${dropEnabled ? " f-img-drop-zone" : ""}${dragOver ? " is-dragover" : ""}`}
|
||||
{...dropZoneProps}
|
||||
>
|
||||
<label className="f-m-label">{t('profile.photoLabel')}</label>
|
||||
{displayImage ? (
|
||||
<div className="f-img-preview-wrap">
|
||||
<img src={displayImage} alt="profile" className="f-img-preview" />
|
||||
{dragOver && <span className="f-img-drop-overlay">{t('profile.dropReplace')}</span>}
|
||||
<button
|
||||
className="f-img-remove"
|
||||
onClick={onRemove}
|
||||
@@ -52,7 +61,16 @@ function ImageUpload({
|
||||
className="f-img-input"
|
||||
disabled={compressing}
|
||||
/>
|
||||
{compressing ? <span>{t('profile.processing')}</span> : <span>{t('profile.addPhoto')}</span>}
|
||||
{compressing ? (
|
||||
<span>{t('profile.processing')}</span>
|
||||
) : dragOver ? (
|
||||
<span>{t('profile.dropRelease')}</span>
|
||||
) : (
|
||||
<span className="f-img-upload-text">
|
||||
<span>{t('profile.addPhoto')}</span>
|
||||
{dropEnabled && <span className="f-img-upload-sub">{t('profile.dropHint')}</span>}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
{imgError && <p className="f-err-msg">{imgError}</p>}
|
||||
@@ -99,27 +117,19 @@ function NameFieldsRow({ form, errors, onChange }) {
|
||||
}
|
||||
|
||||
// ─── Contact fields ─────────────────────────────────────────────────────────
|
||||
function ContactFields({ form, errors, onChange, onPhoneChange }) {
|
||||
// Email в окне профиля не показываем: он не редактируется здесь, но остаётся
|
||||
// в состоянии формы и уходит при сохранении без изменений.
|
||||
function ContactFields({ form, errors, onPhoneChange }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<InputField
|
||||
label={t('profile.phoneLabel')}
|
||||
type="tel"
|
||||
placeholder="+7 (___) ___-__-__"
|
||||
value={form.phone}
|
||||
error={errors.phone}
|
||||
onChange={(e) => onPhoneChange(e.target.value)}
|
||||
/>
|
||||
<InputField
|
||||
label={t('profile.emailLabel')}
|
||||
type="email"
|
||||
placeholder="example@email.com"
|
||||
value={form.email}
|
||||
error={errors.email}
|
||||
onChange={(e) => onChange("email", e.target.value)}
|
||||
/>
|
||||
</>
|
||||
<InputField
|
||||
label={t('profile.phoneLabel')}
|
||||
type="tel"
|
||||
placeholder="+7 (___) ___-__-__"
|
||||
value={form.phone}
|
||||
error={errors.phone}
|
||||
onChange={(e) => onPhoneChange(e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import { formatPhone } from "../../utils/formatPhone";
|
||||
import { useImageUpload } from "../../hooks/useImageUpload";
|
||||
import { useUpdateProfile } from "../../hooks/useUpdateProfile";
|
||||
import { useAuthContext } from "../../context/AuthContext";
|
||||
import { useIsDesktop } from "../../hooks/useIsDesktop";
|
||||
import { useFileDropZone } from "../../hooks/useFileDropZone";
|
||||
import { validateProfileForm, initializeFormState } from "./profileValidation";
|
||||
import {
|
||||
ImageUpload,
|
||||
@@ -30,11 +32,21 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
||||
compressing,
|
||||
fileInputRef,
|
||||
handleFileChange,
|
||||
addFiles,
|
||||
removeImage,
|
||||
getExistingUrlsToKeep,
|
||||
getFilesForUpload,
|
||||
} = useImageUpload(existingImages);
|
||||
|
||||
// Перетаскивание фото (только десктоп). Аватар один: перетащенный файл
|
||||
// заменяет текущее фото, из нескольких берём первый.
|
||||
const isDesktop = useIsDesktop();
|
||||
const { dragOver, zoneProps, strayDropProps } = useFileDropZone({
|
||||
enabled: isDesktop,
|
||||
busy: compressing,
|
||||
onFiles: files => addFiles(Array.from(files).slice(0, 1), { replace: true }),
|
||||
});
|
||||
|
||||
const currentImage = images[0];
|
||||
const displayImage = currentImage?.preview ?? null;
|
||||
|
||||
@@ -88,6 +100,7 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
||||
<div
|
||||
className="f-modal-bg"
|
||||
onClick={e => e.target === e.currentTarget && !saving && onClose()}
|
||||
{...strayDropProps}
|
||||
>
|
||||
<form
|
||||
className="f-modal"
|
||||
@@ -102,6 +115,8 @@ export default function ProfileModal({ onClose, initialData = {} }) {
|
||||
fileInputRef={fileInputRef}
|
||||
onFileChange={handleFileChange}
|
||||
onRemove={handleRemoveImage}
|
||||
dropZoneProps={zoneProps}
|
||||
dragOver={dragOver}
|
||||
/>
|
||||
|
||||
<LoginField
|
||||
|
||||
78
src/components/profile/ProfileModal.test.jsx
Normal file
78
src/components/profile/ProfileModal.test.jsx
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Фото профиля на десктопе можно перетащить в окно (drag & drop).
|
||||
* Аватар один: перетащенный файл заменяет текущее фото.
|
||||
*/
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import ProfileModal from "./ProfileModal";
|
||||
import { useIsDesktop } from "../../hooks/useIsDesktop";
|
||||
import { compressImage } from "../../utils/compressImage";
|
||||
import { useAuthContext } from "../../context/AuthContext";
|
||||
import "../../i18n";
|
||||
|
||||
jest.mock("../../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
|
||||
jest.mock("../../hooks/useUpdateProfile", () => ({
|
||||
useUpdateProfile: () => ({ updateProfile: jest.fn(), loading: false, error: null }),
|
||||
}));
|
||||
// Сжатие через canvas в jsdom не работает и тут не проверяется
|
||||
jest.mock("../../utils/compressImage", () => ({ compressImage: jest.fn() }));
|
||||
jest.mock("../../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||||
|
||||
const PROFILE = { login: "ivan", firstName: "Иван", lastName: "Петров", phone: "", email: "ivan@example.com" };
|
||||
|
||||
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
||||
beforeEach(() => {
|
||||
compressImage.mockImplementation((file) => Promise.resolve(file));
|
||||
useAuthContext.mockReturnValue({ user: { id: 1 }, updateUser: jest.fn(), logout: jest.fn() });
|
||||
let n = 0;
|
||||
URL.createObjectURL = jest.fn(() => `blob:preview-${++n}`);
|
||||
URL.revokeObjectURL = jest.fn();
|
||||
});
|
||||
|
||||
const photo = (name = "me.jpg") => new File(["x"], name, { type: "image/jpeg" });
|
||||
const fileDrag = (files) => ({ dataTransfer: { files, types: ["Files"], dropEffect: "none" } });
|
||||
const photoLabel = () => screen.getByText(/Фото профиля|Profile photo/);
|
||||
|
||||
test("на десктопе перетащенное фото становится фото профиля", async () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
render(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
|
||||
|
||||
fireEvent.drop(photoLabel(), fileDrag([photo()]));
|
||||
|
||||
expect((await screen.findByAltText("profile")).getAttribute("src")).toBe("blob:preview-1");
|
||||
});
|
||||
|
||||
test("на десктопе перетаскивание заменяет текущее фото", async () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
render(<ProfileModal onClose={jest.fn()} initialData={{ ...PROFILE, avatar: "old.jpg" }} />);
|
||||
|
||||
fireEvent.dragEnter(photoLabel(), fileDrag([]));
|
||||
expect(screen.getByText(/Отпустите, чтобы заменить фото|Drop to replace the photo/)).toBeTruthy();
|
||||
|
||||
fireEvent.drop(photoLabel(), fileDrag([photo()]));
|
||||
|
||||
// Старое фото сразу на экране — ждём, пока превью сменится на новое
|
||||
await waitFor(() => expect(screen.getByAltText("profile").getAttribute("src")).toBe("blob:preview-1"));
|
||||
expect(screen.getAllByAltText("profile")).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("из нескольких перетащенных файлов берётся только первый", async () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
render(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
|
||||
const first = photo("first.jpg");
|
||||
|
||||
fireEvent.drop(photoLabel(), fileDrag([first, photo("second.jpg")]));
|
||||
|
||||
await screen.findByAltText("profile");
|
||||
expect(compressImage).toHaveBeenCalledTimes(1);
|
||||
expect(compressImage).toHaveBeenCalledWith(first);
|
||||
});
|
||||
|
||||
test("на мобильном перетаскивание фото выключено", () => {
|
||||
useIsDesktop.mockReturnValue(false);
|
||||
render(<ProfileModal onClose={jest.fn()} initialData={PROFILE} />);
|
||||
|
||||
fireEvent.drop(photoLabel(), fileDrag([photo()]));
|
||||
|
||||
expect(compressImage).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(/или перетащите фото сюда|or drag a photo here/)).toBeNull();
|
||||
});
|
||||
@@ -12,10 +12,6 @@ export function validateProfileForm(form) {
|
||||
errors.lastName = i18n.t('profile.validateSurnameRequired');
|
||||
}
|
||||
|
||||
if (form.email && !form.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
|
||||
errors.email = i18n.t('profile.validateEmailInvalid');
|
||||
}
|
||||
|
||||
if (form.phone && form.phone.replace(/\D/g, "").length < 11) {
|
||||
errors.phone = i18n.t('profile.validatePhoneInvalid');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export function getImageUrl(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 || "nahodkasupport77@gmail.com";
|
||||
|
||||
/**
|
||||
* Подписка на /user/queue/errors (ошибки отправки сообщений чата: пустое или
|
||||
|
||||
@@ -37,9 +37,13 @@ export const EMPTY_FORM = {
|
||||
category: "",
|
||||
location: "",
|
||||
phone: "",
|
||||
// Согласие на показ номера (152-ФЗ). По умолчанию — «только чат»
|
||||
phoneVisible: false,
|
||||
date: "",
|
||||
address: "",
|
||||
rulesAccepted: false,
|
||||
reward: false,
|
||||
rewardText: ""
|
||||
rewardText: "",
|
||||
// Контрольные вопросы находки; пустая строка — одно незаполненное поле
|
||||
verificationQuestions: [""]
|
||||
};
|
||||
|
||||
67
src/hooks/useChatList.js
Normal file
67
src/hooks/useChatList.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useChats } from "./useChats";
|
||||
import { useDeleteChat } from "./useDeleteChat";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { useUnread } from "../context/UnreadContext";
|
||||
|
||||
/**
|
||||
* Список чатов текущего пользователя: загрузка, фоновое обновление при новых
|
||||
* непрочитанных (WS) и удаление с подтверждением. Общая логика мобильной
|
||||
* страницы списка (ChatListPage) и десктопного двухпанельного мессенджера.
|
||||
*/
|
||||
export function useChatList() {
|
||||
const { t } = useTranslation();
|
||||
const { chats, loading, fetchChats } = useChats();
|
||||
const { isAuthenticated } = useAuthContext();
|
||||
const { unreadMap, totalUnread } = useUnread();
|
||||
const { deleteChat } = useDeleteChat();
|
||||
const [deleteError, setDeleteError] = useState("");
|
||||
// Пропускаем первый прогон эффекта по totalUnread: на маунте список уже
|
||||
// грузится первым эффектом, и без этого guard'а через 500 мс уходил бы
|
||||
// второй, повторный запрос (страница "моргала" и грузилась дважды).
|
||||
const unreadWatcherReadyRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
fetchChats();
|
||||
}
|
||||
}, [isAuthenticated, fetchChats]);
|
||||
|
||||
// При поступлении непрочитанного сообщения (WS) обновляем список, чтобы
|
||||
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) return;
|
||||
if (!unreadWatcherReadyRef.current) {
|
||||
unreadWatcherReadyRef.current = true;
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => fetchChats({ silent: true }), 500);
|
||||
return () => clearTimeout(timer);
|
||||
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
|
||||
// суммой не создаст цикл обновлений.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [totalUnread, isAuthenticated, fetchChats]);
|
||||
|
||||
const handleDeleteChat = useCallback(async (chatId) => {
|
||||
if (!window.confirm(t('chat.confirmDeleteChat'))) return false;
|
||||
const result = await deleteChat(chatId);
|
||||
if (result.success) {
|
||||
fetchChats({ silent: true });
|
||||
return true;
|
||||
}
|
||||
setDeleteError(result.error);
|
||||
return false;
|
||||
}, [t, deleteChat, fetchChats]);
|
||||
|
||||
return {
|
||||
chats,
|
||||
loading,
|
||||
fetchChats,
|
||||
unreadMap,
|
||||
isAuthenticated,
|
||||
handleDeleteChat,
|
||||
deleteError,
|
||||
clearDeleteError: () => setDeleteError(""),
|
||||
};
|
||||
}
|
||||
@@ -78,6 +78,41 @@ export function useChats() {
|
||||
return chat;
|
||||
}, []);
|
||||
|
||||
/** Один чат: статус проверки ответов (verificationStatus, claimantId) и собеседник. */
|
||||
const fetchChat = useCallback(async (chatId) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}`);
|
||||
if (!res.ok) throw await readApiError(res);
|
||||
return res.json();
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* «Это моё»: ответы на контрольные вопросы находки. Бэкенд создаёт чат с
|
||||
* ответами первым сообщением; писать дальше можно после подтверждения автором.
|
||||
*/
|
||||
const claimPost = useCallback(async (postId, answers, postInfo) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/${encodeURIComponent(postId)}/claim`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ answers }),
|
||||
});
|
||||
// 429 — лимит заявок, 409 — уже отвечали, 400 — не все ответы
|
||||
if (!res.ok) throw await readApiError(res);
|
||||
const chat = await res.json();
|
||||
cacheChatPost(chat, postInfo);
|
||||
return chat;
|
||||
}, []);
|
||||
|
||||
/** Автор находки подтверждает (approved) или отклоняет ответы; возвращает сообщение-решение. */
|
||||
const decideVerification = useCallback(async (chatId, approved) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/verification`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ approved }),
|
||||
});
|
||||
if (!res.ok) throw await readApiError(res);
|
||||
return res.json();
|
||||
}, []);
|
||||
|
||||
const fetchMessages = useCallback(async (chatId) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
|
||||
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
|
||||
@@ -98,7 +133,87 @@ export function useChats() {
|
||||
}
|
||||
}, [clearChatUnread]);
|
||||
|
||||
return { chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead };
|
||||
/**
|
||||
* Сообщение с фото (и необязательным текстом) — через REST: файлы по
|
||||
* WebSocket не передать. Возвращает сохранённое сообщение; собеседнику
|
||||
* (и нам же) оно придёт и по сокету — дубль отсекается по id.
|
||||
*/
|
||||
const sendPhotoMessage = useCallback(async (chatId, content, files) => {
|
||||
const data = new FormData();
|
||||
if (content) data.append("content", content);
|
||||
files.forEach((file) => data.append("files", file, file.name || "photo.jpg"));
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`, {
|
||||
method: "POST",
|
||||
body: data,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await readApiError(res);
|
||||
console.warn("sendPhotoMessage failed:", err.status, err.serverMessage);
|
||||
throw err;
|
||||
}
|
||||
return res.json();
|
||||
}, []);
|
||||
|
||||
/** Свежие ссылки на вложение ({ url, posterUrl }), если выданные с сообщением истекли. */
|
||||
const refreshAttachmentUrl = useCallback(async (chatId, attachmentId) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/attachments/${attachmentId}/url`);
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
return res.json();
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Видео: 1) ссылка на загрузку, 2) файл прямо в хранилище (через бэкенд с его
|
||||
* лимитом 10 МБ видео не пройдёт), 3) подтверждение — сервер создаёт сообщение
|
||||
* с видео «в обработке», а готовое видео придёт по сокету тем же сообщением.
|
||||
*/
|
||||
const sendVideoMessage = useCallback(async (chatId, content, file, onProgress) => {
|
||||
const ticketRes = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/videos/upload-url`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ contentType: file.type, sizeBytes: file.size }),
|
||||
});
|
||||
if (!ticketRes.ok) throw await readApiError(ticketRes);
|
||||
const { uploadUrl, sourceKey } = await ticketRes.json();
|
||||
|
||||
await uploadWithProgress(uploadUrl, file, onProgress);
|
||||
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/videos`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sourceKey, content: content || null }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await readApiError(res);
|
||||
console.warn("sendVideoMessage failed:", err.status, err.serverMessage);
|
||||
throw err;
|
||||
}
|
||||
return res.json();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead,
|
||||
sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl, fetchChat, claimPost, decideVerification,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT файла по presigned-ссылке с прогрессом (у fetch прогресса отправки нет).
|
||||
* Content-Type должен совпасть с подписанным — иначе хранилище ответит 403.
|
||||
*/
|
||||
function uploadWithProgress(url, file, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("PUT", url);
|
||||
xhr.setRequestHeader("Content-Type", file.type);
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress?.(e.loaded / e.total);
|
||||
};
|
||||
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300
|
||||
? resolve()
|
||||
: reject(new Error(`Upload failed: ${xhr.status}`)));
|
||||
xhr.onerror = () => reject(new Error("Upload failed"));
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
function chatWithUrl(otherUserId, postId, suffix = "") {
|
||||
|
||||
@@ -32,7 +32,13 @@ export function useContactSeller(post) {
|
||||
title: post.title,
|
||||
images: post.images,
|
||||
emoji: post.emoji,
|
||||
type: post.type,
|
||||
city: post.city,
|
||||
status: post.status,
|
||||
phoneVisible: post.phoneVisible,
|
||||
};
|
||||
// У объявления с контрольными вопросами черновик — форма ответов, а не поле ввода
|
||||
const questions = Array.isArray(post.verificationQuestions) ? post.verificationQuestions : [];
|
||||
// Чат не создаём заранее: если переписки ещё нет, открываем черновик,
|
||||
// а чат появится на бэкенде вместе с первым сообщением
|
||||
const chat = await findChat(post.userId, post.id, postInfo);
|
||||
@@ -40,7 +46,7 @@ export function useContactSeller(post) {
|
||||
if (chat) {
|
||||
navigate(`/chats/${chat.id}`);
|
||||
} else {
|
||||
navigate("/chats/new", { state: { otherUserId: post.userId, postId: post.id, post: postInfo } });
|
||||
navigate("/chats/new", { state: { otherUserId: post.userId, postId: post.id, post: postInfo, questions } });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
58
src/hooks/useFileDropZone.js
Normal file
58
src/hooks/useFileDropZone.js
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
const isFileDrag = (e) => Array.from(e.dataTransfer?.types || []).includes("Files");
|
||||
|
||||
/**
|
||||
* Зона для перетаскивания файлов (drag & drop).
|
||||
*
|
||||
* zoneProps вешаются на элемент-зону: подсветка (dragOver) и приём файлов
|
||||
* в onFiles. strayDropProps — на всё окно: файл, отпущенный мимо зоны,
|
||||
* браузер открыл бы вместо сайта, и введённые в форму данные пропали бы.
|
||||
*
|
||||
* dragenter/dragleave приходят и от дочерних элементов зоны, поэтому
|
||||
* считаем глубину, иначе подсветка мигает при движении над содержимым.
|
||||
*
|
||||
* @param {{ enabled: boolean, busy?: boolean, onFiles: (files: FileList) => void }} options
|
||||
* enabled — выключенная зона не вешает обработчики (мобильная раскладка);
|
||||
* busy — файлы ещё обрабатываются: новый drop игнорируется.
|
||||
*/
|
||||
export function useFileDropZone({ enabled, busy = false, onFiles }) {
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const depthRef = useRef(0);
|
||||
|
||||
if (!enabled) return { dragOver: false, zoneProps: {}, strayDropProps: {} };
|
||||
|
||||
const zoneProps = {
|
||||
onDragEnter: (e) => {
|
||||
if (!isFileDrag(e)) return;
|
||||
e.preventDefault();
|
||||
depthRef.current += 1;
|
||||
setDragOver(true);
|
||||
},
|
||||
onDragOver: (e) => {
|
||||
if (!isFileDrag(e)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = busy ? "none" : "copy";
|
||||
},
|
||||
onDragLeave: (e) => {
|
||||
if (!isFileDrag(e)) return;
|
||||
depthRef.current = Math.max(0, depthRef.current - 1);
|
||||
if (depthRef.current === 0) setDragOver(false);
|
||||
},
|
||||
onDrop: (e) => {
|
||||
if (!isFileDrag(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
depthRef.current = 0;
|
||||
setDragOver(false);
|
||||
if (!busy) onFiles(e.dataTransfer.files);
|
||||
},
|
||||
};
|
||||
|
||||
const strayDropProps = {
|
||||
onDragOver: (e) => { if (isFileDrag(e)) e.preventDefault(); },
|
||||
onDrop: (e) => { if (isFileDrag(e)) e.preventDefault(); },
|
||||
};
|
||||
|
||||
return { dragOver, zoneProps, strayDropProps };
|
||||
}
|
||||
@@ -50,13 +50,23 @@ export function useImageUpload(existingUrls = []) {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [existingUrlsKey, hasUserSelected]);
|
||||
|
||||
const handleFileChange = useCallback(async (e) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
/**
|
||||
* Добавляет файлы к списку: проверка типа и размера, сжатие, превью.
|
||||
* Общая точка для выбора через <input type="file"> и перетаскивания (drop).
|
||||
*
|
||||
* replace — заменить текущие фото вместо добавления (одиночный аватар).
|
||||
* Старые фото снимаются только после успешной обработки новых: при ошибке
|
||||
* пользователь остаётся с прежним фото.
|
||||
*/
|
||||
const addFiles = useCallback(async (fileList, { replace = false } = {}) => {
|
||||
const files = Array.from(fileList || []);
|
||||
if (!files.length) return;
|
||||
setImgError("");
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
// Сверяем с ACCEPT, а не с "image/*": у <input> тип отсекает окно выбора,
|
||||
// а при перетаскивании может прилететь что угодно (GIF, HEIC, SVG)
|
||||
if (!ACCEPT.split(",").includes(file.type)) {
|
||||
setImgError(t('imageUpload.invalidType'));
|
||||
return;
|
||||
}
|
||||
@@ -85,7 +95,13 @@ export function useImageUpload(existingUrls = []) {
|
||||
isExisting: false,
|
||||
serverUrl: null,
|
||||
}));
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
setImages(prev => {
|
||||
if (!replace) return [...prev, ...newImages];
|
||||
prev.forEach(img => {
|
||||
if (!img.isExisting && img.preview) URL.revokeObjectURL(img.preview);
|
||||
});
|
||||
return newImages;
|
||||
});
|
||||
} catch {
|
||||
setImgError(t('imageUpload.processingFailed'));
|
||||
} finally {
|
||||
@@ -94,6 +110,8 @@ export function useImageUpload(existingUrls = []) {
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
const handleFileChange = useCallback((e) => addFiles(e.target.files), [addFiles]);
|
||||
|
||||
const removeImage = useCallback((id) => {
|
||||
setImages(prev => {
|
||||
const img = prev.find(i => i.id === id);
|
||||
@@ -104,6 +122,17 @@ export function useImageUpload(existingUrls = []) {
|
||||
});
|
||||
}, []);
|
||||
|
||||
/** Убирает все выбранные фото (например, после отправки сообщения). */
|
||||
const clearImages = useCallback(() => {
|
||||
setImages(prev => {
|
||||
prev.forEach(img => {
|
||||
if (!img.isExisting && img.preview) URL.revokeObjectURL(img.preview);
|
||||
});
|
||||
return [];
|
||||
});
|
||||
setImgError("");
|
||||
}, []);
|
||||
|
||||
const getFilesForUpload = useCallback(() => {
|
||||
return images.filter(i => !i.isExisting).map(i => i.file);
|
||||
}, [images]);
|
||||
@@ -136,7 +165,9 @@ export function useImageUpload(existingUrls = []) {
|
||||
compressing,
|
||||
fileInputRef,
|
||||
handleFileChange,
|
||||
addFiles,
|
||||
removeImage,
|
||||
clearImages,
|
||||
getFilesForUpload,
|
||||
getExistingUrlsToKeep,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState, useCallback } from "react";
|
||||
* Управляет всеми модалками MainFeed через единое состояние,
|
||||
* чтобы гарантировать что открыта максимум одна модалка сразу.
|
||||
*
|
||||
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "postDetail"
|
||||
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "guide" | "postDetail"
|
||||
*/
|
||||
export function useModals() {
|
||||
const [modal, setModal] = useState(null); // { type, payload }
|
||||
|
||||
@@ -8,20 +8,15 @@ const PAGE_SIZE = 50;
|
||||
const MAX_PAGES = 20;
|
||||
|
||||
/**
|
||||
* Объявления пользователя: новый маршрут GET /api/v1/users/{userId}/posts
|
||||
* (Page<PostResponse>). Подгружаем все страницы — «Мои объявления» показываются
|
||||
* целиком, а своих объявлений у пользователя немного.
|
||||
*
|
||||
* @returns {Promise<object[]|null>} null — маршрута нет (старый бэкенд)
|
||||
* Объявления пользователя: GET /api/v1/users/{userId}/posts (Page<PostResponse>).
|
||||
* Подгружаем все страницы — «Мои объявления» показываются целиком, а своих
|
||||
* объявлений у пользователя немного.
|
||||
*/
|
||||
async function fetchUserPostsPaged(userId) {
|
||||
async function fetchUserPosts(userId) {
|
||||
const all = [];
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const params = new URLSearchParams({ page, size: PAGE_SIZE, sort: "createdAt,desc" });
|
||||
const res = await apiFetch(`${API_URL}/api/v1/users/${userId}/posts?${params}`);
|
||||
// Старый бэкенд: маршрута нет (404) либо /users/** закрыт без токена и
|
||||
// неизвестный путь падает в 500 — откатываемся на прежний эндпоинт
|
||||
if (page === 0 && (res.status === 404 || res.status === 405 || res.status >= 500)) return null;
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
const data = await res.json();
|
||||
const items = Array.isArray(data) ? data : (data.content ?? data.items ?? []);
|
||||
@@ -32,15 +27,6 @@ async function fetchUserPostsPaged(userId) {
|
||||
return all;
|
||||
}
|
||||
|
||||
/** Прежний маршрут: GET /api/v1/posts/{userId} — список без пагинации. */
|
||||
async function fetchUserPostsLegacy(userId) {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/${userId}`);
|
||||
if (res.status === 404) return [];
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
const data = await res.json();
|
||||
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает объявления текущего пользователя по userId.
|
||||
*
|
||||
@@ -61,7 +47,7 @@ export function useMyPosts(userId) {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const posts = (await fetchUserPostsPaged(userId)) ?? (await fetchUserPostsLegacy(userId));
|
||||
const posts = await fetchUserPosts(userId);
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
setMyAds(posts.map(ad => ({
|
||||
...ad,
|
||||
|
||||
22
src/hooks/useProfileData.js
Normal file
22
src/hooks/useProfileData.js
Normal file
@@ -0,0 +1,22 @@
|
||||
import { useMemo } from "react";
|
||||
import { getImageUrl } from "../config/authConstants";
|
||||
|
||||
/**
|
||||
* Данные профиля для навигации/аватаров из пользователя AuthContext
|
||||
* (та же нормализация, что в ленте и на странице отзывов).
|
||||
*/
|
||||
export function useProfileData(user) {
|
||||
return useMemo(() => {
|
||||
if (!user) return {};
|
||||
const nameParts = (user.name || "").trim().split(/\s+/);
|
||||
return {
|
||||
login: user.login || "",
|
||||
firstName: user.firstName || nameParts[0] || "",
|
||||
lastName: user.lastName || nameParts.slice(1).join(" ") || "",
|
||||
email: user.email || "",
|
||||
phone: user.phone || "",
|
||||
avatar: getImageUrl(user.avatar),
|
||||
id: user.id,
|
||||
};
|
||||
}, [user]);
|
||||
}
|
||||
42
src/hooks/useRevealPhone.js
Normal file
42
src/hooks/useRevealPhone.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { revealPhone } from "../api/phoneApi";
|
||||
import { describeApiError } from "../api/apiErrors";
|
||||
|
||||
/**
|
||||
* useRevealPhone — кнопка «Показать номер» в карточке объявления.
|
||||
* Браузер решает proof-of-work задачу (доли секунды) и получает номер.
|
||||
*
|
||||
* @param {number|string} postId
|
||||
* @returns {{ phone: string, loading: boolean, error: string, reveal: function, clearError: function }}
|
||||
*/
|
||||
export function useRevealPhone(postId) {
|
||||
const { t } = useTranslation();
|
||||
const [phone, setPhone] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const abortRef = useRef(null);
|
||||
|
||||
// Карточка ушла из ленты — перебор и запросы больше не нужны
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
const reveal = useCallback(async () => {
|
||||
if (loading || phone) return;
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
setPhone(await revealPhone(postId, { signal: controller.signal }));
|
||||
} catch (err) {
|
||||
if (err?.name === "AbortError") return;
|
||||
setError(describeApiError(err, t("postCard.phoneError")));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
}, [loading, phone, postId, t]);
|
||||
|
||||
const clearError = useCallback(() => setError(""), []);
|
||||
|
||||
return { phone, loading, error, reveal, clearError };
|
||||
}
|
||||
96
src/hooks/useVideoAttachment.js
Normal file
96
src/hooks/useVideoAttachment.js
Normal file
@@ -0,0 +1,96 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
// Те же ограничения, что на бэкенде (ChatVideoUploadService, ChatVideoTranscoder)
|
||||
export const VIDEO_TYPES = ["video/mp4", "video/quicktime", "video/webm", "video/3gpp"];
|
||||
export const MAX_VIDEO_MB = 100;
|
||||
export const MAX_VIDEO_SECONDS = 60;
|
||||
|
||||
/**
|
||||
* Длительность видео по метаданным. Браузер может не уметь открыть файл
|
||||
* (например, HEVC из iPhone в Chrome) — тогда null, и длительность проверит сервер.
|
||||
*/
|
||||
export function readVideoDuration(file) {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
const url = URL.createObjectURL(file);
|
||||
const video = document.createElement("video");
|
||||
video.preload = "metadata";
|
||||
let done = false;
|
||||
const finish = (value) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(value);
|
||||
};
|
||||
video.onloadedmetadata = () => finish(Number.isFinite(video.duration) ? video.duration : null);
|
||||
video.onerror = () => finish(null);
|
||||
setTimeout(() => finish(null), 5000);
|
||||
video.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбранное для отправки видео (одно на сообщение): проверка формата, размера
|
||||
* и длительности, превью-ссылка и её освобождение.
|
||||
*/
|
||||
export function useVideoAttachment() {
|
||||
const { t } = useTranslation();
|
||||
const [video, setVideo] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const videoRef = useRef(null);
|
||||
videoRef.current = video;
|
||||
|
||||
const clearVideo = useCallback(() => {
|
||||
setVideo((prev) => {
|
||||
if (prev?.preview) URL.revokeObjectURL(prev.preview);
|
||||
return null;
|
||||
});
|
||||
setError("");
|
||||
}, []);
|
||||
|
||||
/** Проверяет файл и делает его выбранным видео. Возвращает true, если видео принято. */
|
||||
const selectVideo = useCallback(async (file) => {
|
||||
setError("");
|
||||
if (!VIDEO_TYPES.includes(file.type)) {
|
||||
setError(t("chat.videoBadType"));
|
||||
return false;
|
||||
}
|
||||
if (file.size > MAX_VIDEO_MB * 1024 * 1024) {
|
||||
setError(t("chat.videoTooLarge", { max: MAX_VIDEO_MB }));
|
||||
return false;
|
||||
}
|
||||
setChecking(true);
|
||||
try {
|
||||
const duration = await readVideoDuration(file);
|
||||
if (duration != null && duration > MAX_VIDEO_SECONDS + 1) {
|
||||
setError(t("chat.videoTooLong", { max: MAX_VIDEO_SECONDS }));
|
||||
return false;
|
||||
}
|
||||
setVideo((prev) => {
|
||||
if (prev?.preview) URL.revokeObjectURL(prev.preview);
|
||||
return { file, preview: URL.createObjectURL(file), duration };
|
||||
});
|
||||
return true;
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => () => {
|
||||
if (videoRef.current?.preview) URL.revokeObjectURL(videoRef.current.preview);
|
||||
}, []);
|
||||
|
||||
return { video, error, setError, checking, selectVideo, clearVideo };
|
||||
}
|
||||
|
||||
/** «0:07», «1:00» — длительность для подписи на видео. */
|
||||
export function formatDuration(seconds) {
|
||||
if (seconds == null || !Number.isFinite(seconds)) return "";
|
||||
const total = Math.round(seconds);
|
||||
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
||||
}
|
||||
@@ -14,7 +14,36 @@
|
||||
"profile": "Profile",
|
||||
"reviews": "Reviews",
|
||||
"rules": "Platform Rules",
|
||||
"support": "Support"
|
||||
"support": "Support",
|
||||
"about": "About",
|
||||
"guide": "How it works"
|
||||
},
|
||||
"guide": {
|
||||
"bannerTitle": "New here?",
|
||||
"bannerText": "See how the app works — it takes a minute.",
|
||||
"bannerButton": "How it works",
|
||||
"bannerClose": "Hide the tip",
|
||||
"title": "How to use Nakhodka",
|
||||
"intro": "Nakhodka helps return lost things — belongings, documents and pets. You can browse without an account; posting and chatting need a free sign-up.",
|
||||
"searchTitle": "Search the feed or the map",
|
||||
"searchText": "In the feed, switch between “Lost” and “Found”, pick a city and search by words. To see what was lost or found near you, open the “Map”.",
|
||||
"mapTitle": "Check the map",
|
||||
"mapText": "The map opens where you are (if you allow location access). Red pins are lost items, green pins are found ones; tap a pin to open the listing. The address in a listing is a button too — it shows the place on the map.",
|
||||
"createTitle": "Post a listing",
|
||||
"createText": "Tap “+” or “Post a listing”, add photos and a description, and mark the exact place on the map — people will find you faster. After a quick check the listing appears in the feed and on the map.",
|
||||
"chatTitle": "Message the author",
|
||||
"chatText": "The “Write” button opens a chat. Send photos and videos — it makes it easier to prove the item is yours.",
|
||||
"phoneTitle": "Call if allowed",
|
||||
"phoneText": "If the author allowed it, the listing has a “Show number” button. If not, use the chat.",
|
||||
"doneTitle": "Mark it returned",
|
||||
"doneText": "Item is back with its owner? Tap “✓ Returned to owner” in your listing — it will be closed.",
|
||||
"safetyTitle": "Stay safe",
|
||||
"safety1": "Never pay in advance — scammers ask for a “deposit” or a “delivery fee”.",
|
||||
"safety2": "Ask for details or photos that are not in the listing.",
|
||||
"safety3": "Meet in a public place.",
|
||||
"safety4": "Found documents are returned free of charge.",
|
||||
"login": "Log in or sign up",
|
||||
"gotIt": "Got it"
|
||||
},
|
||||
"categories": {
|
||||
"item": "Item",
|
||||
@@ -99,6 +128,8 @@
|
||||
"processing": "Processing...",
|
||||
"addMore": "➕ Add more",
|
||||
"addPhoto": "📷 Add photo",
|
||||
"dropHint": "or drag photos here",
|
||||
"dropRelease": "Drop to add photos",
|
||||
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB · multiple allowed",
|
||||
"categoryLabel": "Category",
|
||||
"mapLabel": "Location on map",
|
||||
@@ -142,7 +173,19 @@
|
||||
"unknownError": "Unknown error",
|
||||
"nextStep": "Next",
|
||||
"backStep": "Back",
|
||||
"mapNoCoords": "This listing has no coordinates, so there is no location to show on the map."
|
||||
"mapNoCoords": "This listing has no coordinates, so there is no location to show on the map.",
|
||||
"phoneConsentCheckbox": "Show my phone number to users who open the listing",
|
||||
"phoneConsentHint": "Only people who tap “Show number” will see it. You can withdraw consent at any time: untick the box when editing and the number is removed from the listing.",
|
||||
"chatOnlyHint": "People will contact you via chat — your phone number is not published.",
|
||||
"verifyQuestionsLabel": "Questions for the owner",
|
||||
"verifyQuestionsHint": "Ask about something the photo doesn't show: what's inside, a sticker, how much cash is in the wallet. To message you, people will have to answer, and they'll see your number only after you confirm the answers.",
|
||||
"verifyQuestionPlaceholder": "E.g.: what's in the inner pocket?",
|
||||
"verifyQuestionAdd": "+ Add question",
|
||||
"verifyQuestionRemove": "Remove question",
|
||||
"verifyQuestionsHintLoss": "Ask something only the person holding the item would know: an engraving, a sticker on the back, what's inside. A scammer who never found it can't answer — and nobody can message you or see your number until you confirm the answers.",
|
||||
"verifyQuestionPlaceholderLoss": "E.g.: what's engraved on the back?",
|
||||
"safetyTitle": "How not to get scammed",
|
||||
"safetyText": "Never send prepayments, deposits or money \"for delivery\" — you don't have to buy your item back. Give the reward only in person, once the item is in your hands. Never share SMS codes or card details."
|
||||
},
|
||||
"feed": {
|
||||
"loading": "Loading ads...",
|
||||
@@ -193,7 +236,17 @@
|
||||
"contactError": "Unable to open the chat. Please try again",
|
||||
"reward": "Reward",
|
||||
"statusModeration": "Under review",
|
||||
"statusRejected": "Rejected"
|
||||
"statusRejected": "Rejected",
|
||||
"showPhone": "Show number",
|
||||
"phoneChecking": "Checking…",
|
||||
"phoneError": "Could not get the number. Message the author in chat",
|
||||
"ownAd": "Your listing",
|
||||
"claimItem": "It's mine",
|
||||
"phoneAfterVerification": "Number after check",
|
||||
"phoneAfterVerificationHint": "Answer the author's questions: the number opens once they confirm your answers",
|
||||
"verifiedClaims": "Contact after answering questions",
|
||||
"phoneSafetyHint": "Don't prepay and never share SMS codes",
|
||||
"claimFound": "I found it"
|
||||
},
|
||||
"chat": {
|
||||
"title": "Chat",
|
||||
@@ -205,7 +258,49 @@
|
||||
"noChats": "You have no chats yet",
|
||||
"deleteChat": "Delete chat",
|
||||
"confirmDeleteChat": "Are you sure you want to delete this chat?",
|
||||
"user": "User"
|
||||
"user": "User",
|
||||
"photoPreview": "Photo",
|
||||
"attachPhoto": "Attach photo",
|
||||
"removePhoto": "Remove photo",
|
||||
"openPhoto": "Open photo",
|
||||
"tooManyPhotos": "No more than {{max}} photos per message",
|
||||
"videoPreview": "Video",
|
||||
"attachMedia": "Attach photo or video",
|
||||
"videoProcessing": "Processing video…",
|
||||
"videoFailed": "Could not process the video",
|
||||
"videoSendError": "Could not send the video",
|
||||
"videoSeparately": "A video is sent as a separate message, without photos",
|
||||
"videoBadType": "Unsupported video format (use MP4, MOV, WebM or 3GP)",
|
||||
"videoTooLarge": "Video is larger than {{max}} MB",
|
||||
"videoTooLong": "Video is longer than {{max}} seconds",
|
||||
"postInfo": "Listing for this chat",
|
||||
"postRemoved": "Listing deleted",
|
||||
"postClosed": "Closed",
|
||||
"postUnavailable": "The listing was deleted or unpublished. The conversation is kept.",
|
||||
"showOnMap": "Show on map",
|
||||
"safetyTitle": "Beware of scammers",
|
||||
"safetyText": "Don't send prepayments, deposits or money \"for delivery\", never share SMS codes or card details. Meet in a public place.",
|
||||
"safetyHide": "Hide",
|
||||
"newAccount": "New account: registered less than a week ago",
|
||||
"fraudPrepayment": "They are asking for money upfront. Returning a found item never requires prepayment — this is a common scam.",
|
||||
"fraudCardData": "This message contains card details. Never share your card number, CVV or expiry date.",
|
||||
"fraudSmsCode": "They are asking for an SMS code or account access. Never share codes: this is how accounts and money get stolen.",
|
||||
"claimTitle": "Answer the author's questions",
|
||||
"claimIntro": "The author will check your answers. Until they confirm, you can't write in the chat or see their number.",
|
||||
"claimAnswerPlaceholder": "Your answer",
|
||||
"claimSubmit": "Send answers",
|
||||
"claimSending": "Sending…",
|
||||
"claimError": "Couldn't send the answers",
|
||||
"claimCardTitle": "Answers to the questions",
|
||||
"verifyPending": "The author is checking your answers. You can write once they confirm.",
|
||||
"verifyRejected": "The author didn't confirm your answers.",
|
||||
"verifyApproved": "The author confirmed your answers.",
|
||||
"verifyOwnerPrompt": "Do the answers match what only the owner would know? Once confirmed, they can write and will see your number.",
|
||||
"verifyOwnerRejected": "You rejected the answers. If that was a mistake, you can still confirm.",
|
||||
"verifyApprove": "Confirm",
|
||||
"verifyReject": "Reject",
|
||||
"verifyError": "Couldn't save the decision",
|
||||
"revealPhone": "Show author's number"
|
||||
},
|
||||
"reviews": {
|
||||
"anonymous": "Anonymous",
|
||||
@@ -437,6 +532,9 @@
|
||||
"deletePhoto": "Delete photo",
|
||||
"processing": "Processing...",
|
||||
"addPhoto": "📷 Add photo",
|
||||
"dropHint": "or drag a photo here",
|
||||
"dropRelease": "Drop to add the photo",
|
||||
"dropReplace": "Drop to replace the photo",
|
||||
"photoHint": "JPEG / PNG / WebP · up to {{maxSize}} MB",
|
||||
"loginLabel": "Login",
|
||||
"nameLabel": "First name",
|
||||
@@ -579,7 +677,8 @@
|
||||
"processingFailed": "Failed to process the image"
|
||||
},
|
||||
"common": {
|
||||
"close": "Close"
|
||||
"close": "Close",
|
||||
"error": "Failed to load"
|
||||
},
|
||||
"fullscreenAd": {
|
||||
"label": "Ad",
|
||||
@@ -617,5 +716,51 @@
|
||||
"openLink": "Open ad in a new tab",
|
||||
"closeIn": "Close in {{seconds}}s",
|
||||
"close": "Close ad"
|
||||
},
|
||||
"desktop": {
|
||||
"createPost": "Post a listing",
|
||||
"typeAll": "All",
|
||||
"feedSub": {
|
||||
"home": "Lost and found items and pets",
|
||||
"items": "Documents, keys, electronics, bags and more",
|
||||
"pets": "Lost and found animals",
|
||||
"myads": "Your listings: edit, close or bring them back to the feed"
|
||||
},
|
||||
"shown": "Showing {{count}}",
|
||||
"searchResults": "Search results",
|
||||
"resetFilters": "Reset filters",
|
||||
"ctaTitle": "Lost or found something?",
|
||||
"ctaText": "Post a listing in a minute — people nearby will see it.",
|
||||
"mapCardTitle": "Listings on the map",
|
||||
"mapCardText": "See where things were lost and found nearby",
|
||||
"mapCardBtn": "Open map",
|
||||
"fresh": "Fresh listings",
|
||||
"seeAll": "All",
|
||||
"freshEmpty": "No new listings yet",
|
||||
"guestTitle": "Welcome",
|
||||
"guestText": "Sign in to post listings and message authors",
|
||||
"myProfile": "My profile",
|
||||
"settings": "Settings",
|
||||
"collapse": "Collapse menu",
|
||||
"expand": "Expand menu",
|
||||
"map": {
|
||||
"title": "Listings map",
|
||||
"inArea": "In this area: {{count}}",
|
||||
"emptyArea": "No listings here yet",
|
||||
"emptyAreaSub": "Zoom out or move to another area",
|
||||
"catAll": "All categories",
|
||||
"loading": "Loading listings…",
|
||||
"showOnMap": "Show on map",
|
||||
"open": "Open"
|
||||
},
|
||||
"chats": {
|
||||
"selectTitle": "Select a chat",
|
||||
"selectSub": "Open a conversation on the left to keep talking with the listing author",
|
||||
"search": "Search chats",
|
||||
"nothingFound": "Nothing found",
|
||||
"newChat": "New chat"
|
||||
},
|
||||
"adminSection": "Administration",
|
||||
"reviewsSub": "What people think about Nakhodka — and a place for your opinion"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,36 @@
|
||||
"profile": "Профиль",
|
||||
"reviews": "Отзывы",
|
||||
"rules": "Правила площадки",
|
||||
"support": "Поддержка"
|
||||
"support": "Поддержка",
|
||||
"about": "О сервисе",
|
||||
"guide": "Инструкция"
|
||||
},
|
||||
"guide": {
|
||||
"bannerTitle": "Ты здесь впервые?",
|
||||
"bannerText": "Посмотри, как пользоваться приложением — это займёт минуту.",
|
||||
"bannerButton": "Как пользоваться",
|
||||
"bannerClose": "Скрыть подсказку",
|
||||
"title": "Как пользоваться Находкой",
|
||||
"intro": "Находка помогает вернуть потерянное — вещи, документы и питомцев. Смотреть ленту можно без входа, а для объявлений и чата нужна регистрация — она бесплатная.",
|
||||
"searchTitle": "Ищи в ленте или на карте",
|
||||
"searchText": "В ленте переключай «Потери» и «Находки», выбирай город и ищи по словам. А чтобы понять, что потеряли или нашли рядом с тобой, открой «Карту».",
|
||||
"mapTitle": "Смотри на карте",
|
||||
"mapText": "Карта сразу покажет место, где ты сейчас (если разрешишь геолокацию). Красные метки — потери, зелёные — находки; нажми на метку, и откроется объявление. Адрес в объявлении — тоже кнопка: она покажет место на карте.",
|
||||
"createTitle": "Размести объявление",
|
||||
"createText": "Нажми «+» или «Разместить объявление», добавь фото и описание и точно отметь место на карте — так тебя быстрее найдут. После короткой проверки объявление появится в ленте и на карте.",
|
||||
"chatTitle": "Пиши автору",
|
||||
"chatText": "Кнопка «Написать» откроет чат. Отправляй фото и видео — так проще доказать, что вещь твоя.",
|
||||
"phoneTitle": "Звони, если можно",
|
||||
"phoneText": "Если автор разрешил, в объявлении есть кнопка «Показать номер». Если её нет — пиши в чат.",
|
||||
"doneTitle": "Отметь, что вернулось",
|
||||
"doneText": "Вещь у владельца? Нажми «✓ Вернулось к владельцу» в своём объявлении — оно закроется.",
|
||||
"safetyTitle": "Будь осторожен",
|
||||
"safety1": "Не переводи деньги заранее — мошенники просят «залог» или оплату «за доставку».",
|
||||
"safety2": "Попроси назвать приметы или прислать фото, которых нет в объявлении.",
|
||||
"safety3": "Встречайся в людном месте.",
|
||||
"safety4": "Найденные документы возвращают бесплатно.",
|
||||
"login": "Войти или зарегистрироваться",
|
||||
"gotIt": "Понятно"
|
||||
},
|
||||
"categories": {
|
||||
"item": "Вещь",
|
||||
@@ -99,6 +128,8 @@
|
||||
"processing": "Обработка...",
|
||||
"addMore": "➕ Добавить ещё",
|
||||
"addPhoto": "📷 Добавить фото",
|
||||
"dropHint": "или перетащите фото сюда",
|
||||
"dropRelease": "Отпустите, чтобы добавить фото",
|
||||
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ · можно несколько",
|
||||
"categoryLabel": "Категория",
|
||||
"mapLabel": "Место на карте",
|
||||
@@ -142,7 +173,19 @@
|
||||
"unknownError": "Неизвестная ошибка",
|
||||
"nextStep": "Далее",
|
||||
"backStep": "Назад",
|
||||
"mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего."
|
||||
"mapNoCoords": "У объявления не указаны координаты — показывать место на карте нечего.",
|
||||
"phoneConsentCheckbox": "Показывать мой номер телефона пользователям, открывшим объявление",
|
||||
"phoneConsentHint": "Номер увидят только те, кто нажмёт «Показать номер». Согласие можно отозвать в любой момент — снимите галочку при редактировании, и номер будет удалён из объявления.",
|
||||
"chatOnlyHint": "С вами свяжутся через чат — номер телефона не публикуется.",
|
||||
"verifyQuestionsLabel": "Вопросы для владельца",
|
||||
"verifyQuestionsHint": "Спросите то, чего не видно на фото: что внутри, какая наклейка, сколько денег в кошельке. Чтобы написать вам, человеку придётся ответить, а номер он увидит, только когда вы подтвердите ответы.",
|
||||
"verifyQuestionPlaceholder": "Например: что лежит во внутреннем кармане?",
|
||||
"verifyQuestionAdd": "+ Добавить вопрос",
|
||||
"verifyQuestionRemove": "Убрать вопрос",
|
||||
"verifyQuestionsHintLoss": "Спросите то, что знает только тот, у кого вещь в руках: что выгравировано, какая наклейка на обороте, что лежит внутри. Мошенник, который вещь не находил, не ответит — а написать вам и увидеть номер можно только после того, как вы подтвердите ответы.",
|
||||
"verifyQuestionPlaceholderLoss": "Например: что выгравировано на обороте?",
|
||||
"safetyTitle": "Как не попасться мошенникам",
|
||||
"safetyText": "Не переводите предоплату, залог и деньги «за доставку» — вещь не нужно выкупать. Вознаграждение отдавайте только при встрече, когда вещь у вас в руках. Никому не называйте коды из СМС и данные карты."
|
||||
},
|
||||
"feed": {
|
||||
"loading": "Загружаем объявления...",
|
||||
@@ -193,7 +236,17 @@
|
||||
"contactError": "Не удалось открыть чат. Попробуйте ещё раз",
|
||||
"reward": "Вознаграждение",
|
||||
"statusModeration": "На модерации",
|
||||
"statusRejected": "Отклонено"
|
||||
"statusRejected": "Отклонено",
|
||||
"showPhone": "Показать номер",
|
||||
"phoneChecking": "Проверка…",
|
||||
"phoneError": "Не удалось получить номер. Напишите автору в чат",
|
||||
"ownAd": "Ваше объявление",
|
||||
"claimItem": "Это моё",
|
||||
"phoneAfterVerification": "Номер — после проверки",
|
||||
"phoneAfterVerificationHint": "Ответьте на вопросы автора: номер откроется, когда он подтвердит ответы",
|
||||
"verifiedClaims": "Связь — после ответов на вопросы",
|
||||
"phoneSafetyHint": "Не переводите предоплату и не называйте коды из СМС",
|
||||
"claimFound": "Я нашёл"
|
||||
},
|
||||
"chat": {
|
||||
"title": "Чат",
|
||||
@@ -205,7 +258,49 @@
|
||||
"noChats": "У вас пока нет чатов",
|
||||
"deleteChat": "Удалить чат",
|
||||
"confirmDeleteChat": "Вы уверены, что хотите удалить этот чат?",
|
||||
"user": "Пользователь"
|
||||
"user": "Пользователь",
|
||||
"photoPreview": "Фото",
|
||||
"attachPhoto": "Прикрепить фото",
|
||||
"removePhoto": "Убрать фото",
|
||||
"openPhoto": "Открыть фото",
|
||||
"tooManyPhotos": "Не больше {{max}} фото в одном сообщении",
|
||||
"videoPreview": "Видео",
|
||||
"attachMedia": "Прикрепить фото или видео",
|
||||
"videoProcessing": "Видео обрабатывается…",
|
||||
"videoFailed": "Не удалось обработать видео",
|
||||
"videoSendError": "Не удалось отправить видео",
|
||||
"videoSeparately": "Видео отправляется отдельным сообщением, без фото",
|
||||
"videoBadType": "Этот формат видео не поддерживается (нужен MP4, MOV, WebM или 3GP)",
|
||||
"videoTooLarge": "Видео больше {{max}} МБ",
|
||||
"videoTooLong": "Видео длиннее {{max}} секунд",
|
||||
"postInfo": "Объявление этого чата",
|
||||
"postRemoved": "Объявление удалено",
|
||||
"postClosed": "Закрыто",
|
||||
"postUnavailable": "Объявление удалено или снято с публикации. Переписка сохранилась.",
|
||||
"showOnMap": "Показать на карте",
|
||||
"safetyTitle": "Осторожно, мошенники",
|
||||
"safetyText": "Не переводите предоплату, залог и деньги «за доставку», не называйте коды из СМС и данные карты. Встречайтесь в людном месте.",
|
||||
"safetyHide": "Скрыть",
|
||||
"newAccount": "Новый аккаунт: собеседник зарегистрировался меньше недели назад",
|
||||
"fraudPrepayment": "Собеседник просит деньги заранее. Возврат вещи не требует предоплаты — это частая схема мошенников.",
|
||||
"fraudCardData": "В сообщении данные карты. Никому не сообщайте номер карты, CVV и срок действия.",
|
||||
"fraudSmsCode": "Просят код из СМС или доступ к Госуслугам. Никогда не называйте коды: так крадут аккаунты и деньги.",
|
||||
"claimTitle": "Ответьте на вопросы автора",
|
||||
"claimIntro": "Автор объявления проверит ответы. Пока он их не подтвердит, писать в чат и видеть номер нельзя.",
|
||||
"claimAnswerPlaceholder": "Ваш ответ",
|
||||
"claimSubmit": "Отправить ответы",
|
||||
"claimSending": "Отправляем…",
|
||||
"claimError": "Не удалось отправить ответы",
|
||||
"claimCardTitle": "Ответы на вопросы",
|
||||
"verifyPending": "Автор проверяет ваши ответы. Написать можно будет после подтверждения.",
|
||||
"verifyRejected": "Автор не подтвердил ваши ответы.",
|
||||
"verifyApproved": "Автор подтвердил ваши ответы.",
|
||||
"verifyOwnerPrompt": "Совпадают ли ответы с тем, что знает только владелец? После подтверждения собеседник сможет писать и увидит ваш номер.",
|
||||
"verifyOwnerRejected": "Вы отклонили ответы. Если ошиблись, их можно подтвердить.",
|
||||
"verifyApprove": "Подтвердить",
|
||||
"verifyReject": "Отклонить",
|
||||
"verifyError": "Не удалось сохранить решение",
|
||||
"revealPhone": "Показать номер автора"
|
||||
},
|
||||
"reviews": {
|
||||
"anonymous": "Аноним",
|
||||
@@ -437,6 +532,9 @@
|
||||
"deletePhoto": "Удалить фото",
|
||||
"processing": "Обработка...",
|
||||
"addPhoto": "📷 Добавить фото",
|
||||
"dropHint": "или перетащите фото сюда",
|
||||
"dropRelease": "Отпустите, чтобы добавить фото",
|
||||
"dropReplace": "Отпустите, чтобы заменить фото",
|
||||
"photoHint": "JPEG / PNG / WebP · до {{maxSize}} МБ",
|
||||
"loginLabel": "Логин",
|
||||
"nameLabel": "Имя",
|
||||
@@ -579,7 +677,8 @@
|
||||
"processingFailed": "Не удалось обработать изображение"
|
||||
},
|
||||
"common": {
|
||||
"close": "Закрыть"
|
||||
"close": "Закрыть",
|
||||
"error": "Ошибка загрузки"
|
||||
},
|
||||
"fullscreenAd": {
|
||||
"label": "Реклама",
|
||||
@@ -617,5 +716,51 @@
|
||||
"openLink": "Открыть рекламу в новой вкладке",
|
||||
"closeIn": "Закрыть через {{seconds}}с",
|
||||
"close": "Закрыть рекламу"
|
||||
},
|
||||
"desktop": {
|
||||
"createPost": "Разместить объявление",
|
||||
"typeAll": "Все",
|
||||
"feedSub": {
|
||||
"home": "Потерянные и найденные вещи и питомцы",
|
||||
"items": "Документы, ключи, электроника, сумки и другое",
|
||||
"pets": "Потерявшиеся и найденные животные",
|
||||
"myads": "Ваши объявления: редактируйте, закрывайте, возвращайте в ленту"
|
||||
},
|
||||
"shown": "Показано {{count}}",
|
||||
"searchResults": "Результаты поиска",
|
||||
"resetFilters": "Сбросить фильтры",
|
||||
"ctaTitle": "Потеряли или нашли?",
|
||||
"ctaText": "Разместите объявление за минуту — его увидят люди рядом с вами.",
|
||||
"mapCardTitle": "Объявления на карте",
|
||||
"mapCardText": "Смотрите, где теряли и находили вещи поблизости",
|
||||
"mapCardBtn": "Открыть карту",
|
||||
"fresh": "Свежие объявления",
|
||||
"seeAll": "Все",
|
||||
"freshEmpty": "Пока нет новых объявлений",
|
||||
"guestTitle": "Добро пожаловать",
|
||||
"guestText": "Войдите, чтобы размещать объявления и писать авторам",
|
||||
"myProfile": "Мой профиль",
|
||||
"settings": "Настройки",
|
||||
"collapse": "Свернуть меню",
|
||||
"expand": "Развернуть меню",
|
||||
"map": {
|
||||
"title": "Карта объявлений",
|
||||
"inArea": "В этой области: {{count}}",
|
||||
"emptyArea": "Здесь пока нет объявлений",
|
||||
"emptyAreaSub": "Отдалите карту или переместитесь в другой район",
|
||||
"catAll": "Все категории",
|
||||
"loading": "Загружаем объявления…",
|
||||
"showOnMap": "Показать на карте",
|
||||
"open": "Открыть"
|
||||
},
|
||||
"chats": {
|
||||
"selectTitle": "Выберите чат",
|
||||
"selectSub": "Откройте переписку слева, чтобы продолжить общение с автором объявления",
|
||||
"search": "Поиск по чатам",
|
||||
"nothingFound": "Ничего не найдено",
|
||||
"newChat": "Новый чат"
|
||||
},
|
||||
"adminSection": "Администрирование",
|
||||
"reviewsSub": "Что пользователи думают о Находке — и место для вашего мнения"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { useEffect, useState, useCallback, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useChats } from "../hooks/useChats";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { useUnread } from "../context/UnreadContext";
|
||||
import { getPostForChat } from "../stores/chatPostStore";
|
||||
import { useDeleteChat } from "../hooks/useDeleteChat";
|
||||
import { useChatList } from "../hooks/useChatList";
|
||||
import ChatHeader from "../components/chat/ChatHeader";
|
||||
import ChatListItem from "../components/chat/ChatListItem";
|
||||
import Toast from "../components/Toast";
|
||||
@@ -13,46 +9,10 @@ import Toast from "../components/Toast";
|
||||
export default function ChatListPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { chats, loading, fetchChats } = useChats();
|
||||
const { isAuthenticated } = useAuthContext();
|
||||
const { unreadMap, totalUnread } = useUnread();
|
||||
const { deleteChat } = useDeleteChat();
|
||||
const [deleteError, setDeleteError] = useState("");
|
||||
// Пропускаем первый прогон эффекта по totalUnread: на маунте список уже
|
||||
// грузится первым эффектом, и без этого guard'а через 500 мс уходил бы
|
||||
// второй, повторный запрос (страница "моргала" и грузилась дважды).
|
||||
const unreadWatcherReadyRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
fetchChats();
|
||||
}
|
||||
}, [isAuthenticated, fetchChats]);
|
||||
|
||||
// При поступлении непрочитанного сообщения (WS) обновляем список, чтобы
|
||||
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) return;
|
||||
if (!unreadWatcherReadyRef.current) {
|
||||
unreadWatcherReadyRef.current = true;
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => fetchChats({ silent: true }), 500);
|
||||
return () => clearTimeout(timer);
|
||||
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
|
||||
// суммой не создаст цикл обновлений.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [totalUnread, isAuthenticated, fetchChats]);
|
||||
|
||||
const handleDeleteChat = useCallback(async (chatId) => {
|
||||
if (!window.confirm(t('chat.confirmDeleteChat'))) return;
|
||||
const result = await deleteChat(chatId);
|
||||
if (result.success) {
|
||||
fetchChats({ silent: true });
|
||||
} else {
|
||||
setDeleteError(result.error);
|
||||
}
|
||||
}, [t, deleteChat, fetchChats]);
|
||||
const {
|
||||
chats, loading, unreadMap, isAuthenticated,
|
||||
handleDeleteChat, deleteError, clearDeleteError,
|
||||
} = useChatList();
|
||||
|
||||
const goBack = () => navigate("/feed");
|
||||
const openChat = (chatId) => navigate(`/chats/${chatId}`);
|
||||
@@ -100,9 +60,9 @@ export default function ChatListPage() {
|
||||
<Toast
|
||||
message={deleteError}
|
||||
type="error"
|
||||
onDismiss={() => setDeleteError("")}
|
||||
onDismiss={clearDeleteError}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,28 @@ import { getImageUrl } from "../config/authConstants";
|
||||
import ChatHeader from "../components/chat/ChatHeader";
|
||||
import MessageBubble from "../components/chat/MessageBubble";
|
||||
import ChatInputBar from "../components/chat/ChatInputBar";
|
||||
import ChatPhotoViewer from "../components/chat/ChatPhotoViewer";
|
||||
import ChatPostMeta from "../components/chat/ChatPostMeta";
|
||||
import ChatSafetyNotice from "../components/chat/ChatSafetyNotice";
|
||||
import ClaimForm from "../components/chat/ClaimForm";
|
||||
import VerificationPanel from "../components/chat/VerificationPanel";
|
||||
import PostDetailModal from "../components/PostDetailModal";
|
||||
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
||||
import { ACCEPT as IMAGE_ACCEPT, useImageUpload } from "../hooks/useImageUpload";
|
||||
import { VIDEO_TYPES, useVideoAttachment } from "../hooks/useVideoAttachment";
|
||||
import Toast from "../components/Toast";
|
||||
|
||||
export default function ChatPage() {
|
||||
// Тот же лимит, что ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE на бэкенде
|
||||
const MAX_PHOTOS_PER_MESSAGE = 10;
|
||||
|
||||
/**
|
||||
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
|
||||
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
|
||||
* а onActivity сообщает списку чатов, что превью пора обновить.
|
||||
*
|
||||
* @param {{ embedded?: boolean, onActivity?: () => void }} [props]
|
||||
*/
|
||||
export default function ChatPage({ embedded = false, onActivity } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const { chatId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -23,28 +42,55 @@ export default function ChatPage() {
|
||||
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
|
||||
const draft = chatId ? null : location.state;
|
||||
const [startingChat, setStartingChat] = useState(false);
|
||||
const { fetchMessages, markAsRead, startChat } = useChats();
|
||||
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl,
|
||||
fetchChat, claimPost, decideVerification } = useChats();
|
||||
const { clearChatUnread } = useUnread();
|
||||
const { user, isAuthenticated } = useAuthContext();
|
||||
const [messages, setMessages] = useState([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const [sendError, setSendError] = useState("");
|
||||
const [showPost, setShowPost] = useState(false);
|
||||
const [sendingPhotos, setSendingPhotos] = useState(false);
|
||||
const [viewer, setViewer] = useState(null);
|
||||
const upload = useImageUpload();
|
||||
const { addFiles: addUploadFiles } = upload;
|
||||
const [photoLimitError, setPhotoLimitError] = useState("");
|
||||
const videoAttach = useVideoAttachment();
|
||||
const { selectVideo } = videoAttach;
|
||||
// Прогресс загрузки видео в хранилище, 0..1; null — загрузки нет
|
||||
const [videoProgress, setVideoProgress] = useState(null);
|
||||
// Чат с бэкенда: статус проверки ответов на вопросы объявления и дата регистрации собеседника
|
||||
const [chatInfo, setChatInfo] = useState(null);
|
||||
const [deciding, setDeciding] = useState(false);
|
||||
// Черновик к объявлению с контрольными вопросами: вместо поля ввода — форма ответов
|
||||
const claimQuestions = draft?.questions?.length ? draft.questions : null;
|
||||
// id вложений, для которых уже запрашивали свежую ссылку, — без повторов по кругу
|
||||
const refreshedPhotosRef = useRef(new Set());
|
||||
const messagesEndRef = useRef(null);
|
||||
const pageRef = useRef(null);
|
||||
|
||||
const myUserId = user?.id;
|
||||
|
||||
/** Мержит новое сообщение по id — защита от дублей (REST + WS эхо). */
|
||||
/**
|
||||
* Мержит сообщение по id — защита от дублей (REST + WS эхо). Уже известное
|
||||
* сообщение заменяется: так приходит видео, которое закончило обрабатываться.
|
||||
*/
|
||||
const addMessage = useCallback((msg) => {
|
||||
setMessages((prev) => {
|
||||
if (msg.id != null && prev.some((m) => m.id === msg.id)) return prev;
|
||||
if (msg.id != null && prev.some((m) => m.id === msg.id)) {
|
||||
return prev.map((m) => (m.id === msg.id ? { ...m, ...msg } : m));
|
||||
}
|
||||
return sortMessages([...prev, msg]);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleIncoming = useCallback((msg) => {
|
||||
addMessage(msg);
|
||||
// Автор подтвердил или отклонил ответы: снимаем или оставляем блокировку ввода
|
||||
if (msg.kind === "VERIFICATION" && msg.verificationStatus) {
|
||||
setChatInfo((prev) => (prev ? { ...prev, verificationStatus: msg.verificationStatus } : prev));
|
||||
}
|
||||
}, [addMessage]);
|
||||
|
||||
// Сервер отклонил отправку (пустое/длинное сообщение, нет доступа к чату)
|
||||
@@ -82,11 +128,14 @@ export default function ChatPage() {
|
||||
})
|
||||
.catch(() => setLoadError(t('chats.loadError')));
|
||||
|
||||
setChatInfo(null);
|
||||
fetchChat(chatId).then(setChatInfo).catch(() => {});
|
||||
|
||||
markAsRead(chatId);
|
||||
clearChatUnread(chatId);
|
||||
|
||||
return () => setActiveChatId(null);
|
||||
}, [chatId, fetchMessages, markAsRead, clearChatUnread, t]);
|
||||
}, [chatId, fetchMessages, markAsRead, clearChatUnread, fetchChat, t]);
|
||||
|
||||
// Шапка и поле ввода лежат поверх ленты сообщений — меряем их высоту в
|
||||
// CSS-переменные --chat-header-height / --chat-input-height, чтобы первое
|
||||
@@ -96,9 +145,17 @@ export default function ChatPage() {
|
||||
const header = page?.querySelector(".chat-header");
|
||||
const inputArea = page?.querySelector(".chat-input-area");
|
||||
if (!header || !inputArea) return;
|
||||
const list = page.querySelector(".chat-messages");
|
||||
let inputHeight = inputArea.offsetHeight;
|
||||
const update = () => {
|
||||
// Поле ввода выросло (появились превью фото), а пользователь был внизу
|
||||
// ленты — оставляем его внизу, иначе последнее сообщение уйдёт под превью
|
||||
const grew = inputArea.offsetHeight > inputHeight;
|
||||
const atBottom = list && list.scrollHeight - list.scrollTop - list.clientHeight < inputArea.offsetHeight + 80;
|
||||
inputHeight = inputArea.offsetHeight;
|
||||
page.style.setProperty("--chat-header-height", `${header.offsetHeight}px`);
|
||||
page.style.setProperty("--chat-input-height", `${inputArea.offsetHeight}px`);
|
||||
page.style.setProperty("--chat-input-height", `${inputHeight}px`);
|
||||
if (grew && atBottom) list.scrollTop = list.scrollHeight;
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
@@ -114,6 +171,46 @@ export default function ChatPage() {
|
||||
const handleSend = useCallback((e) => {
|
||||
e.preventDefault();
|
||||
const trimmed = input.trim();
|
||||
const photos = draft ? [] : upload.getFilesForUpload();
|
||||
|
||||
const video = draft ? null : videoAttach.video;
|
||||
if (video) {
|
||||
if (sendingPhotos) return;
|
||||
setSendingPhotos(true);
|
||||
setVideoProgress(0);
|
||||
sendVideoMessage(chatId, trimmed, video.file, setVideoProgress)
|
||||
.then((msg) => {
|
||||
addMessage(msg);
|
||||
setInput("");
|
||||
videoAttach.clearVideo();
|
||||
onActivity?.();
|
||||
})
|
||||
// 429 — лимит видео; 400 — формат, размер; сбой загрузки в хранилище
|
||||
.catch((err) => setSendError(describeApiError(err, t('chat.videoSendError'))))
|
||||
.finally(() => {
|
||||
setSendingPhotos(false);
|
||||
setVideoProgress(null);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (photos.length > 0) {
|
||||
if (sendingPhotos || upload.compressing) return;
|
||||
setSendingPhotos(true);
|
||||
sendPhotoMessage(chatId, trimmed, photos)
|
||||
.then((msg) => {
|
||||
addMessage(msg);
|
||||
setInput("");
|
||||
upload.clearImages();
|
||||
setPhotoLimitError("");
|
||||
onActivity?.();
|
||||
})
|
||||
// 429 — лимит отправки фото; 400 — не картинка, слишком много фото и т.п.
|
||||
.catch((err) => setSendError(describeApiError(err, t('chats.sendError'))))
|
||||
.finally(() => setSendingPhotos(false));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!trimmed) return;
|
||||
|
||||
if (draft) {
|
||||
@@ -122,6 +219,7 @@ export default function ChatPage() {
|
||||
startChat(draft.otherUserId, draft.postId, trimmed, draft.post)
|
||||
.then((chat) => {
|
||||
setInput("");
|
||||
onActivity?.();
|
||||
navigate(`/chats/${chat.id}`, { replace: true });
|
||||
})
|
||||
// 429 — лимит начала чатов; 400 — чат с собой, чужое объявление и т.п.
|
||||
@@ -136,17 +234,107 @@ export default function ChatPage() {
|
||||
return;
|
||||
}
|
||||
setInput("");
|
||||
}, [input, sendMessage, t, draft, startingChat, startChat, navigate]);
|
||||
onActivity?.();
|
||||
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity,
|
||||
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage, videoAttach, sendVideoMessage]);
|
||||
|
||||
const post = draft ? draft.post : getPostForChat(chatId);
|
||||
// «Это моё»: чат создаётся вместе с ответами, дальше ждём решения автора
|
||||
const handleClaim = useCallback((answers) => {
|
||||
if (startingChat) return;
|
||||
setStartingChat(true);
|
||||
claimPost(draft.postId, answers, draft.post)
|
||||
.then((chat) => {
|
||||
onActivity?.();
|
||||
navigate(`/chats/${chat.id}`, { replace: true });
|
||||
})
|
||||
// 429 — лимит заявок; 409 — уже отвечали; 400 — не все ответы
|
||||
.catch((err) => setSendError(describeApiError(err, t('chat.claimError'))))
|
||||
.finally(() => setStartingChat(false));
|
||||
}, [startingChat, claimPost, draft, onActivity, navigate, t]);
|
||||
|
||||
const handleDecide = useCallback((approved) => {
|
||||
if (deciding) return;
|
||||
setDeciding(true);
|
||||
decideVerification(chatId, approved)
|
||||
.then((msg) => {
|
||||
addMessage(msg);
|
||||
setChatInfo((prev) => ({ ...prev, verificationStatus: msg.verificationStatus }));
|
||||
onActivity?.();
|
||||
})
|
||||
.catch((err) => setSendError(describeApiError(err, t('chat.verifyError'))))
|
||||
.finally(() => setDeciding(false));
|
||||
}, [deciding, decideVerification, chatId, addMessage, onActivity, t]);
|
||||
|
||||
/**
|
||||
* Выбор файлов: фото (до 10) или одно видео. Видео уходит отдельным
|
||||
* сообщением — вместе с фото его не отправить.
|
||||
*/
|
||||
const addPhotos = useCallback((fileList) => {
|
||||
const files = Array.from(fileList || []);
|
||||
const videos = files.filter((f) => f.type.startsWith("video/"));
|
||||
if (videos.length > 0) {
|
||||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||||
if (videos.length > 1 || files.length > videos.length || upload.images.length > 0) {
|
||||
setPhotoLimitError(t('chat.videoSeparately'));
|
||||
return;
|
||||
}
|
||||
setPhotoLimitError("");
|
||||
selectVideo(videos[0]);
|
||||
return;
|
||||
}
|
||||
if (videoAttach.video) {
|
||||
setPhotoLimitError(t('chat.videoSeparately'));
|
||||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||||
return;
|
||||
}
|
||||
if (upload.images.length + files.length > MAX_PHOTOS_PER_MESSAGE) {
|
||||
setPhotoLimitError(t('chat.tooManyPhotos', { max: MAX_PHOTOS_PER_MESSAGE }));
|
||||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||||
return;
|
||||
}
|
||||
setPhotoLimitError("");
|
||||
addUploadFiles(files);
|
||||
}, [upload.images.length, upload.fileInputRef, addUploadFiles, t, selectVideo, videoAttach.video]);
|
||||
|
||||
// Ссылки на фото и видео временные: если чат долго открыт и ссылка истекла, берём свежую
|
||||
const handlePhotoError = useCallback((message, photo) => {
|
||||
if (!chatId || photo.id == null || refreshedPhotosRef.current.has(photo.id)) return;
|
||||
refreshedPhotosRef.current.add(photo.id);
|
||||
refreshAttachmentUrl(chatId, photo.id)
|
||||
.then(({ url, posterUrl }) => setMessages((prev) => prev.map((m) => (m.id !== message.id ? m : {
|
||||
...m,
|
||||
attachments: m.attachments.map((a) => (a.id === photo.id ? { ...a, url, posterUrl } : a)),
|
||||
}))))
|
||||
.catch(() => {});
|
||||
}, [chatId, refreshAttachmentUrl]);
|
||||
|
||||
const post = draft ? draft.post : (getPostForChat(chatId) || chatInfo?.post);
|
||||
const verificationStatus = chatInfo?.verificationStatus ?? null;
|
||||
const isClaimant = chatInfo?.claimantId != null && String(chatInfo.claimantId) === String(myUserId);
|
||||
// Заявитель пишет только после подтверждения ответов (бэкенд отклонит и сам)
|
||||
const inputLocked = isClaimant && verificationStatus != null && verificationStatus !== "APPROVED";
|
||||
const postImg = getImageUrl(post?.images?.[0]);
|
||||
const postId = post?.id ?? draft?.postId;
|
||||
|
||||
return (
|
||||
<div className="f-app">
|
||||
<div className="chat-page chat-page--open" ref={pageRef}>
|
||||
// «Перейти к объявлению» — на карту с фокусом на нём (тот же URL, что у
|
||||
// кнопки адреса в ленте). Без координат на карте фокусироваться не на чем.
|
||||
const hasCoords = (ad) => ad?.latitude != null && ad?.longitude != null
|
||||
&& Number.isFinite(Number(ad.latitude)) && Number.isFinite(Number(ad.longitude));
|
||||
const openOnMap = (ad) => {
|
||||
if (!hasCoords(ad)) return;
|
||||
const params = new URLSearchParams({ view: "map", post: String(ad.id), lat: String(ad.latitude), lng: String(ad.longitude) });
|
||||
navigate(`/feed?${params.toString()}`);
|
||||
};
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<div className={`chat-page chat-page--open${embedded ? " chat-page--embedded" : ""}`} ref={pageRef}>
|
||||
<ChatHeader
|
||||
title={post?.title || t('chat.title')}
|
||||
onBack={() => navigate("/chats")}
|
||||
subtitle={<ChatPostMeta post={post} t={t} className="chat-header-meta" />}
|
||||
onInfo={postId != null ? () => setShowPost(true) : undefined}
|
||||
infoLabel={t('chat.postInfo')}
|
||||
avatar={postImg ? (
|
||||
<img src={postImg} alt="" className="chat-header-avatar-img" />
|
||||
) : (
|
||||
@@ -155,25 +343,85 @@ export default function ChatPage() {
|
||||
/>
|
||||
|
||||
<div className="chat-messages">
|
||||
<ChatSafetyNotice key={chatId ?? "draft"} chatId={chatId} otherUserCreatedAt={chatInfo?.otherUserCreatedAt} t={t} />
|
||||
{loadError && <div className="chat-empty">{loadError}</div>}
|
||||
{!loadError && messages.length === 0 && (
|
||||
{claimQuestions && (
|
||||
<ClaimForm questions={claimQuestions} onSubmit={handleClaim} sending={startingChat} t={t} />
|
||||
)}
|
||||
{!loadError && !claimQuestions && messages.length === 0 && (
|
||||
<div className="chat-empty">{t('chat.noMessages')}</div>
|
||||
)}
|
||||
{messages.map((m) => (
|
||||
<MessageBubble key={m.id} message={m} isMine={m.senderId === myUserId} />
|
||||
<MessageBubble
|
||||
key={m.id}
|
||||
message={m}
|
||||
isMine={m.senderId === myUserId}
|
||||
onOpenPhoto={(photos, index) => setViewer({ photos, index })}
|
||||
onPhotoError={handlePhotoError}
|
||||
/>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
<ChatInputBar
|
||||
locked={!!claimQuestions || inputLocked}
|
||||
notice={(
|
||||
<VerificationPanel
|
||||
status={verificationStatus}
|
||||
isClaimant={isClaimant}
|
||||
postId={postId}
|
||||
phoneVisible={!!(chatInfo?.post?.phoneVisible ?? post?.phoneVisible)}
|
||||
onDecide={handleDecide}
|
||||
deciding={deciding}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
input={input}
|
||||
onInputChange={setInput}
|
||||
onSend={handleSend}
|
||||
connected={draft ? !startingChat : connected}
|
||||
placeholder={t('chat.messagePlaceholder')}
|
||||
sending={sendingPhotos}
|
||||
/* В черновике (/chats/new) чата ещё нет — фото можно со второго сообщения */
|
||||
attach={draft ? undefined : {
|
||||
images: upload.images,
|
||||
addFiles: addPhotos,
|
||||
removeImage: upload.removeImage,
|
||||
fileInputRef: upload.fileInputRef,
|
||||
compressing: upload.compressing || videoAttach.checking,
|
||||
error: photoLimitError || videoAttach.error || upload.imgError,
|
||||
accept: [IMAGE_ACCEPT, ...VIDEO_TYPES].join(","),
|
||||
video: videoAttach.video,
|
||||
removeVideo: videoAttach.clearVideo,
|
||||
videoProgress,
|
||||
label: t('chat.attachMedia'),
|
||||
removeLabel: t('chat.removePhoto'),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{viewer && (
|
||||
<ChatPhotoViewer photos={viewer.photos} startIndex={viewer.index} onClose={() => setViewer(null)} />
|
||||
)}
|
||||
|
||||
{showPost && (
|
||||
<PostDetailModal
|
||||
postId={postId}
|
||||
onClose={() => setShowPost(false)}
|
||||
onLocationClick={openOnMap}
|
||||
compact={false}
|
||||
hideContact
|
||||
fallbackTitle={post?.title}
|
||||
footer={(ad) => ad.status !== POST_STATUS_CLOSED && hasCoords(ad) && (
|
||||
<div className="chat-post-modal-actions">
|
||||
<button type="button" className="chat-post-open-btn" onClick={() => openOnMap(ad)}>
|
||||
{t('chat.showOnMap')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sendError && (
|
||||
<Toast
|
||||
message={sendError}
|
||||
@@ -181,6 +429,8 @@ export default function ChatPage() {
|
||||
onDismiss={() => setSendError("")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
return embedded ? content : <div className="f-app">{content}</div>;
|
||||
}
|
||||
@@ -10,10 +10,16 @@ import { formatPhone } from "../utils/formatPhone";
|
||||
import MapModal from "./MapModal";
|
||||
import ClearableField from "../components/ClearableField";
|
||||
import AddressAutocomplete from "../components/AddressAutocomplete";
|
||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||
import { useFileDropZone } from "../hooks/useFileDropZone";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
|
||||
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
|
||||
const TITLE_MAX_LENGTH = 255;
|
||||
const REWARD_TEXT_MAX_LENGTH = 255;
|
||||
// Контрольные вопросы находки (PostFieldLimits): не больше 3, до 200 символов
|
||||
const MAX_VERIFY_QUESTIONS = 3;
|
||||
const VERIFY_QUESTION_MAX_LENGTH = 200;
|
||||
// Поля первого шага формы: ошибку в них нужно показывать на шаге 1
|
||||
const STEP_ONE_FIELDS = ["title", "description"];
|
||||
/**
|
||||
@@ -28,8 +34,13 @@ const STEP_ONE_FIELDS = ["title", "description"];
|
||||
export default function CreateUpdatePost({ onClose, onSuccess, initialData, adminMode = false }) {
|
||||
const isEdit = !!initialData;
|
||||
const { t } = useTranslation();
|
||||
const isDesktop = useIsDesktop();
|
||||
const { user } = useAuthContext();
|
||||
// Телефон из профиля подставляем, чтобы не вводить его в каждом объявлении.
|
||||
// В админ-режиме правится чужое объявление — телефон админа туда не нужен.
|
||||
const profilePhone = !adminMode && user?.phone ? formatPhone(user.phone) : "";
|
||||
|
||||
const [form, setForm] = useState(
|
||||
const [form, setForm] = useState(() => (
|
||||
isEdit
|
||||
? {
|
||||
type: (initialData.type || "loss").toLowerCase(),
|
||||
@@ -37,15 +48,18 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
description: initialData.description || "",
|
||||
category: initialData.category || "",
|
||||
date: initialData.date || "",
|
||||
phone: initialData.phone || "",
|
||||
phone: initialData.phone || profilePhone,
|
||||
phoneVisible: !!initialData.phoneVisible,
|
||||
address: initialData.address || initialData.city || "",
|
||||
rulesAccepted: true,
|
||||
reward: initialData.reward ?? false,
|
||||
rewardText: initialData.rewardText
|
||||
|| (initialData.reward ? t('post.rewardDefault') : "")
|
||||
|| (initialData.reward ? t('post.rewardDefault') : ""),
|
||||
verificationQuestions: initialData.verificationQuestions?.length
|
||||
? [...initialData.verificationQuestions] : [""],
|
||||
}
|
||||
: EMPTY_FORM
|
||||
);
|
||||
: { ...EMPTY_FORM, phone: profilePhone }
|
||||
));
|
||||
|
||||
const [rulesModalOpen, setRulesModalOpen] = useState(false);
|
||||
const [mapModalOpen, setMapModalOpen] = useState(false);
|
||||
@@ -58,11 +72,19 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
compressing,
|
||||
fileInputRef,
|
||||
handleFileChange,
|
||||
addFiles,
|
||||
removeImage,
|
||||
getFilesForUpload,
|
||||
getExistingUrlsToKeep,
|
||||
} = useImageUpload(isEdit ? initialData.images : []);
|
||||
|
||||
// Перетаскивание фото (drag & drop) — только на десктопе
|
||||
const { dragOver, zoneProps: dropZoneHandlers, strayDropProps: blockStrayDrop } = useFileDropZone({
|
||||
enabled: isDesktop,
|
||||
busy: compressing,
|
||||
onFiles: addFiles,
|
||||
});
|
||||
|
||||
const { save, loading: saving, error: apiError } = usePostMutation({ adminMode });
|
||||
|
||||
const [resultModal, setResultModal] = useState(null); // null | "success" | "blocked"
|
||||
@@ -111,9 +133,21 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
data.append("title", form.title.trim());
|
||||
data.append("description", form.description.trim());
|
||||
data.append("category", form.category);
|
||||
data.append("phone", form.phone.trim());
|
||||
data.append("reward", form.reward ? "true" : "false");
|
||||
if (form.reward) data.append("rewardText", (form.rewardText || "").trim());
|
||||
// Без согласия номер не отправляем: бэкенд его и не сохранит.
|
||||
// Админ согласие не меняет — правит только номер, если автор его показывает
|
||||
const phoneVisible = adminMode ? !!initialData?.phoneVisible : form.phoneVisible;
|
||||
if (!adminMode) data.append("phoneVisible", phoneVisible ? "true" : "false");
|
||||
if (phoneVisible) data.append("phone", form.phone.trim());
|
||||
// У находки вознаграждения нет: галочка, оставшаяся от типа «Потеря», не уходит
|
||||
const reward = form.reward && form.type !== "found";
|
||||
data.append("reward", reward ? "true" : "false");
|
||||
if (reward) data.append("rewardText", (form.rewardText || "").trim());
|
||||
// Шлём всегда, даже пустой массив: так удаление вопросов при правке сохранится.
|
||||
// Админ их не правит: его эндпоинт поле не принимает
|
||||
if (!adminMode) {
|
||||
const questions = (form.verificationQuestions || []).map(q => q.trim()).filter(Boolean);
|
||||
data.append("verificationQuestions", JSON.stringify(questions));
|
||||
}
|
||||
if (form.date) data.append("date", form.date);
|
||||
|
||||
const files = getFilesForUpload();
|
||||
@@ -153,7 +187,10 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
<>
|
||||
<div
|
||||
className="f-modal-bg"
|
||||
onClick={e => e.target === e.currentTarget && !loading && onClose()}
|
||||
// На десктопе форма закрывается только крестиком: случайный клик мимо
|
||||
// окна не должен терять заполненные поля
|
||||
onClick={e => !isDesktop && e.target === e.currentTarget && !loading && onClose()}
|
||||
{...blockStrayDrop}
|
||||
>
|
||||
<div className="f-modal">
|
||||
|
||||
@@ -222,8 +259,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
{errors.description && <p className="f-err-msg">{errors.description}</p>}
|
||||
</div>
|
||||
|
||||
{/* Фотографии */}
|
||||
<div className="f-m-group">
|
||||
{/* Фотографии: на десктопе вся группа — зона для перетаскивания */}
|
||||
<div
|
||||
className={`f-m-group${isDesktop ? " f-img-drop-zone" : ""}${dragOver ? " is-dragover" : ""}`}
|
||||
{...dropZoneHandlers}
|
||||
>
|
||||
<label className="f-m-label">{t('post.photosLabel')}</label>
|
||||
|
||||
{uploadedImages.length > 0 && (
|
||||
@@ -256,8 +296,13 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
/>
|
||||
{compressing ? (
|
||||
<span>{t('post.processing')}</span>
|
||||
) : dragOver ? (
|
||||
<span>{t('post.dropRelease')}</span>
|
||||
) : (
|
||||
<span>{uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}</span>
|
||||
<span className="f-img-upload-text">
|
||||
<span>{uploadedImages.length > 0 ? t('post.addMore') : t('post.addPhoto')}</span>
|
||||
{isDesktop && <span className="f-img-upload-sub">{t('post.dropHint')}</span>}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
@@ -325,7 +370,26 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
{errors.map && <p className="f-err-msg">{errors.map}</p>}
|
||||
</div>
|
||||
|
||||
{/* Телефон */}
|
||||
{/* Телефон: по умолчанию связь только через чат. Номер — персональные
|
||||
данные (152-ФЗ), показываем его только с явного согласия автора */}
|
||||
{!adminMode && (
|
||||
<div className="f-m-group">
|
||||
<label className="f-reward-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.phoneVisible}
|
||||
onChange={e => set("phoneVisible", e.target.checked)}
|
||||
/>
|
||||
<span className="f-reward-checkmark"/>
|
||||
<span className="f-reward-text">{t('post.phoneConsentCheckbox')}</span>
|
||||
</label>
|
||||
<p className="f-hint">
|
||||
{form.phoneVisible ? t('post.phoneConsentHint') : t('post.chatOnlyHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(adminMode ? !!initialData?.phoneVisible : form.phoneVisible) && (
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.phoneLabel')}</label>
|
||||
<ClearableField onClear={() => set("phone", "")} visible={!!form.phone}>
|
||||
@@ -339,8 +403,56 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
</ClearableField>
|
||||
{errors.phone && <p className="f-err-msg">{errors.phone}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Вознаграждение */}
|
||||
{/* Как не попасться мошенникам: главная схема — «нашёл, оплатите доставку» */}
|
||||
{!adminMode && (
|
||||
<div className="f-m-group f-safety-note" role="note">
|
||||
<div className="f-safety-title">🛡️ {t('post.safetyTitle')}</div>
|
||||
<p className="f-safety-text">{t('post.safetyText')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Контрольные вопросы: у потери отсекают «нашёл, оплатите доставку» от тех,
|
||||
кто вещь в руках не держал, у находки — «это моё» по одному фото */}
|
||||
{!adminMode && (
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.verifyQuestionsLabel')}</label>
|
||||
<p className="f-hint">
|
||||
{form.type === "found" ? t('post.verifyQuestionsHint') : t('post.verifyQuestionsHintLoss')}
|
||||
</p>
|
||||
{(form.verificationQuestions || [""]).map((question, i) => (
|
||||
<div key={i} className="f-verify-question">
|
||||
<ClearableField
|
||||
onClear={() => set("verificationQuestions", form.verificationQuestions.length > 1
|
||||
? form.verificationQuestions.filter((_, j) => j !== i)
|
||||
: [""])}
|
||||
visible={!!question || form.verificationQuestions.length > 1}
|
||||
>
|
||||
<input
|
||||
className="f-m-field"
|
||||
type="text"
|
||||
placeholder={form.type === "found"
|
||||
? t('post.verifyQuestionPlaceholder') : t('post.verifyQuestionPlaceholderLoss')}
|
||||
maxLength={VERIFY_QUESTION_MAX_LENGTH}
|
||||
value={question}
|
||||
onChange={e => set("verificationQuestions",
|
||||
form.verificationQuestions.map((q, j) => (j === i ? e.target.value : q)))}
|
||||
/>
|
||||
</ClearableField>
|
||||
</div>
|
||||
))}
|
||||
{(form.verificationQuestions || []).length < MAX_VERIFY_QUESTIONS && (
|
||||
<button type="button" className="f-verify-add"
|
||||
onClick={() => set("verificationQuestions", [...(form.verificationQuestions || []), ""])}>
|
||||
{t('post.verifyQuestionAdd')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Вознаграждение — только для потери */}
|
||||
{form.type !== "found" && (
|
||||
<div className="f-m-group">
|
||||
<label className="f-reward-checkbox">
|
||||
<input
|
||||
@@ -362,8 +474,9 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{form.reward && (
|
||||
{form.reward && form.type !== "found" && (
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.rewardLabel')}</label>
|
||||
<ClearableField onClear={() => set("rewardText", "")} visible={!!form.rewardText}>
|
||||
|
||||
237
src/pages/CreateUpdatePost.test.jsx
Normal file
237
src/pages/CreateUpdatePost.test.jsx
Normal file
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
||||
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
||||
* Там же на десктопе фото можно перетащить в форму (drag & drop).
|
||||
* Номер — только с согласием на показ (по умолчанию «только чат»);
|
||||
* после согласия он подставляется из профиля, если в объявлении его нет.
|
||||
*/
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import CreateUpdatePost from "./CreateUpdatePost";
|
||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||
import { compressImage } from "../utils/compressImage";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import "../i18n";
|
||||
|
||||
jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
|
||||
jest.mock("../hooks/usePostMutation", () => ({
|
||||
usePostMutation: () => ({ save: jest.fn(), loading: false, error: null }),
|
||||
}));
|
||||
// Сжатие через canvas в jsdom не работает и тут не проверяется
|
||||
jest.mock("../utils/compressImage", () => ({ compressImage: jest.fn() }));
|
||||
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||||
|
||||
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
||||
beforeEach(() => {
|
||||
compressImage.mockImplementation((file) => Promise.resolve(file));
|
||||
useAuthContext.mockReturnValue({ user: null });
|
||||
URL.createObjectURL = jest.fn(() => "blob:preview");
|
||||
URL.revokeObjectURL = jest.fn();
|
||||
});
|
||||
|
||||
const ADD_PHOTO = /Добавить фото|Add photo/;
|
||||
|
||||
function fileDrag(files) {
|
||||
return { dataTransfer: { files, types: ["Files"], dropEffect: "none" } };
|
||||
}
|
||||
|
||||
function renderForm() {
|
||||
const onClose = jest.fn();
|
||||
const { container } = render(<CreateUpdatePost onClose={onClose} />);
|
||||
// У фона и крестика нет роли/подписи — ищем по классу, как их видит пользователь
|
||||
// eslint-disable-next-line testing-library/no-container, testing-library/no-node-access
|
||||
return { onClose, backdrop: container.querySelector(".f-modal-bg") };
|
||||
}
|
||||
|
||||
test("на десктопе клик по фону не закрывает форму", () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
const { onClose, backdrop } = renderForm();
|
||||
|
||||
fireEvent.click(backdrop);
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("на десктопе форма закрывается крестиком", () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
const { onClose, backdrop } = renderForm();
|
||||
|
||||
// eslint-disable-next-line testing-library/no-node-access
|
||||
fireEvent.click(backdrop.querySelector(".f-close-btn"));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("на мобильном клик по фону закрывает форму", () => {
|
||||
useIsDesktop.mockReturnValue(false);
|
||||
const { onClose, backdrop } = renderForm();
|
||||
|
||||
fireEvent.click(backdrop);
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("клик внутри окна не закрывает форму", () => {
|
||||
useIsDesktop.mockReturnValue(false);
|
||||
const { onClose } = renderForm();
|
||||
|
||||
fireEvent.click(screen.getByText(/Новое объявление|New ad/));
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("на десктопе перетащенное фото добавляется в форму", async () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
renderForm();
|
||||
const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
|
||||
|
||||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
|
||||
|
||||
// После добавления первого фото кнопка становится «Добавить ещё»
|
||||
expect(await screen.findByText(/Добавить ещё|Add more/)).toBeTruthy();
|
||||
expect(compressImage).toHaveBeenCalledWith(photo);
|
||||
});
|
||||
|
||||
test("на десктопе файл над зоной подсвечивает её подсказкой", () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
renderForm();
|
||||
|
||||
fireEvent.dragEnter(screen.getByText(ADD_PHOTO), fileDrag([]));
|
||||
|
||||
expect(screen.getByText(/Отпустите, чтобы добавить фото|Drop to add photos/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("перетащенный файл неподходящего типа не добавляется", async () => {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
renderForm();
|
||||
const gif = new File(["x"], "anim.gif", { type: "image/gif" });
|
||||
|
||||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([gif]));
|
||||
|
||||
expect(await screen.findByText(/Только изображения|Images only/)).toBeTruthy();
|
||||
expect(compressImage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("на мобильном перетаскивание фото выключено", () => {
|
||||
useIsDesktop.mockReturnValue(false);
|
||||
renderForm();
|
||||
const photo = new File(["x"], "cat.jpg", { type: "image/jpeg" });
|
||||
|
||||
fireEvent.drop(screen.getByText(ADD_PHOTO), fileDrag([photo]));
|
||||
|
||||
expect(compressImage).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(/или перетащите фото сюда|or drag photos here/)).toBeNull();
|
||||
});
|
||||
|
||||
const PROFILE_PHONE = "+7 (999) 111-22-33";
|
||||
const PHONE_PLACEHOLDER = "+7 (___) ___-__-__";
|
||||
const CONSENT = /Показывать мой номер|Show my phone number/;
|
||||
|
||||
/** Рендерит форму и переходит на второй шаг, где находятся согласие и «Телефон». */
|
||||
function openPhoneStep(props = {}) {
|
||||
useIsDesktop.mockReturnValue(true);
|
||||
render(<CreateUpdatePost onClose={jest.fn()} {...props} />);
|
||||
if (!props.initialData) {
|
||||
fireEvent.change(screen.getByPlaceholderText(/Кошелёк|wallet/i), { target: { value: "Ключи" } });
|
||||
fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } });
|
||||
}
|
||||
fireEvent.click(screen.getByText(/^(Далее|Next)/));
|
||||
}
|
||||
|
||||
const phoneField = () => screen.queryByPlaceholderText(PHONE_PLACEHOLDER);
|
||||
|
||||
test("новое объявление: по умолчанию «только чат» — номер не запрашивается", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||||
openPhoneStep();
|
||||
|
||||
expect(screen.getByLabelText(CONSENT).checked).toBe(false);
|
||||
expect(phoneField()).toBeNull();
|
||||
expect(screen.getByText(/номер телефона не публикуется|phone number is not published/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("новое объявление: после согласия телефон подставляется из профиля", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||||
openPhoneStep();
|
||||
|
||||
fireEvent.click(screen.getByLabelText(CONSENT));
|
||||
|
||||
expect(phoneField().value).toBe(PROFILE_PHONE);
|
||||
});
|
||||
|
||||
test("согласие без номера не даёт опубликовать", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: "" } });
|
||||
openPhoneStep();
|
||||
|
||||
fireEvent.click(screen.getByLabelText(CONSENT));
|
||||
fireEvent.click(screen.getByText(/Разместить объявление|Publish/));
|
||||
|
||||
expect(phoneField().value).toBe("");
|
||||
expect(screen.getByText(/Введите номер телефона|Enter a phone number/)).toBeTruthy();
|
||||
});
|
||||
|
||||
const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" };
|
||||
|
||||
test("редактирование: телефон объявления не заменяется телефоном профиля", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "+7 (900) 000-00-00" } });
|
||||
|
||||
expect(screen.getByLabelText(CONSENT).checked).toBe(true);
|
||||
expect(phoneField().value).toBe("+7 (900) 000-00-00");
|
||||
});
|
||||
|
||||
test("редактирование объявления «только чат»: согласие не включается само", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null } });
|
||||
|
||||
expect(screen.getByLabelText(CONSENT).checked).toBe(false);
|
||||
expect(phoneField()).toBeNull();
|
||||
});
|
||||
|
||||
test("админ не может включить показ номера за автора", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||
openPhoneStep({ initialData: { ...POST, phoneVisible: false, phone: null }, adminMode: true });
|
||||
|
||||
expect(screen.queryByLabelText(CONSENT)).toBeNull();
|
||||
expect(phoneField()).toBeNull();
|
||||
});
|
||||
|
||||
test("админ правит номер объявления с согласием: свой телефон не подставляется", () => {
|
||||
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||
openPhoneStep({ initialData: { ...POST, phoneVisible: true, phone: "" }, adminMode: true });
|
||||
|
||||
expect(screen.queryByLabelText(CONSENT)).toBeNull();
|
||||
expect(phoneField().value).toBe("");
|
||||
});
|
||||
|
||||
const FOUND = { id: 2, type: "FOUND", title: "Кошелёк", description: "Коричневый", category: "KEYS" };
|
||||
const QUESTION_PLACEHOLDER = /внутреннем кармане|inner pocket/;
|
||||
const LOSS_QUESTION_PLACEHOLDER = /выгравировано|engraved/;
|
||||
|
||||
test("находка: можно задать до трёх контрольных вопросов", () => {
|
||||
openPhoneStep({ initialData: { ...FOUND, verificationQuestions: ["Что внутри?"] } });
|
||||
|
||||
expect(screen.getAllByPlaceholderText(QUESTION_PLACEHOLDER)[0].value).toBe("Что внутри?");
|
||||
fireEvent.click(screen.getByText(/Добавить вопрос|Add question/));
|
||||
fireEvent.click(screen.getByText(/Добавить вопрос|Add question/));
|
||||
|
||||
expect(screen.getAllByPlaceholderText(QUESTION_PLACEHOLDER)).toHaveLength(3);
|
||||
expect(screen.queryByText(/Добавить вопрос|Add question/)).toBeNull();
|
||||
});
|
||||
|
||||
test("потеря: вопросы задаёт тот, кто потерял, — чтобы отсечь «нашёл, оплатите доставку»", () => {
|
||||
openPhoneStep({ initialData: POST });
|
||||
|
||||
expect(screen.getByPlaceholderText(LOSS_QUESTION_PLACEHOLDER)).toBeTruthy();
|
||||
expect(screen.getByText(/Мошенник, который вещь не находил|scammer who never found/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("в форме объявления — предупреждение о предоплате", () => {
|
||||
openPhoneStep();
|
||||
|
||||
expect(screen.getByText(/Не переводите предоплату|Never send prepayments/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("админ не видит вопросов и предупреждения автору", () => {
|
||||
openPhoneStep({ initialData: POST, adminMode: true });
|
||||
|
||||
expect(screen.queryByPlaceholderText(LOSS_QUESTION_PLACEHOLDER)).toBeNull();
|
||||
});
|
||||
@@ -11,6 +11,8 @@ import CityFilterLegacy from "../components/CityFilter";
|
||||
import { ProfileModal } from "../components/profile";
|
||||
import AuthModal from "../components/AuthModal";
|
||||
import RulesModal from "./RulesModal";
|
||||
import GuideModal from "../components/GuideModal";
|
||||
import GuestGuideBanner from "../components/GuestGuideBanner";
|
||||
import FeedTopBar from "../components/feed/FeedTopBar";
|
||||
import FeedSearchBar from "../components/feed/FeedSearchBar";
|
||||
import CityQuickFilterLegacy from "../components/feed/CityQuickFilter";
|
||||
@@ -18,6 +20,8 @@ import CityQuickFilterLegacy from "../components/feed/CityQuickFilter";
|
||||
import FeedContent from "../components/feed/FeedContent";
|
||||
import PullToRefresh from "../components/feed/PullToRefresh";
|
||||
import MapView from "../components/MapView";
|
||||
import DesktopFeedHeaderLegacy from "../components/desktop/DesktopFeedHeader";
|
||||
import DesktopMapViewLegacy from "../components/desktop/DesktopMapView";
|
||||
import PostDetailModal from "../components/PostDetailModal";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { useCities } from "../hooks/useCities";
|
||||
@@ -42,6 +46,8 @@ import type { ComponentType } from "react";
|
||||
const CityFilter = CityFilterLegacy as unknown as ComponentType<any>;
|
||||
const CityQuickFilter = CityQuickFilterLegacy as unknown as ComponentType<any>;
|
||||
const CreateUpdatePost = CreateUpdatePostLegacy as unknown as ComponentType<any>;
|
||||
const DesktopFeedHeader = DesktopFeedHeaderLegacy as unknown as ComponentType<any>;
|
||||
const DesktopMapView = DesktopMapViewLegacy as unknown as ComponentType<any>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type AnyAds = any[];
|
||||
@@ -198,6 +204,21 @@ export default function MainFeed() {
|
||||
}
|
||||
}, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Десктопная навигация с других страниц (чаты, отзывы): раздел ленты
|
||||
// или сразу форма создания объявления.
|
||||
useEffect(() => {
|
||||
const state = location.state as { desktopNav?: string; desktopAction?: string } | null;
|
||||
if (!state?.desktopNav && !state?.desktopAction) return;
|
||||
if (state.desktopNav && ["home", "items", "pets", "myads"].includes(state.desktopNav)) {
|
||||
setActiveNav(state.desktopNav);
|
||||
}
|
||||
if (state.desktopAction === "create") {
|
||||
if (isAuthenticated) modals.open("create");
|
||||
else modals.open("auth");
|
||||
}
|
||||
navigate(`${location.pathname}${location.search}`, { replace: true, state: null });
|
||||
}, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// При загрузке приложения подтягиваем свежие данные профиля (аватар и т.д.)
|
||||
// с бэка, чтобы нижняя навигация и профиль отражали изменения с других
|
||||
// устройств, а не устаревший кэш контекста. Дергаем один раз на пользователя.
|
||||
@@ -226,6 +247,9 @@ export default function MainFeed() {
|
||||
// вкладки (вещи/питомцы) и фильтра «потеря/находка» — их применяет сервер.
|
||||
useEffect(() => {
|
||||
if (activeNav === "myads" || activeNav === "map") return;
|
||||
// На десктопе поиск и фильтры живут прямо в ленте — загрузкой занимается
|
||||
// отдельный эффект ниже (desktopLoadKeyRef), здесь запрос не дублируем.
|
||||
if (isDesktop && !isSearchView) return;
|
||||
if (!isSearchView && selectedCities.length === 0 && !searchQuery.trim()) {
|
||||
feed.loadFeed(0, "", false, feedFilters);
|
||||
}
|
||||
@@ -244,6 +268,28 @@ export default function MainFeed() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchQuery, feedFiltersKey, isSearchView]);
|
||||
|
||||
// Десктоп: поиск и города всегда в шапке ленты (без отдельной вкладки
|
||||
// «Поиск»), поэтому текст/города/фильтры применяются сразу, текст — с
|
||||
// дебаунсом. Ключ последней загрузки не даёт перезапрашивать ленту при
|
||||
// возврате с карты, если фильтры не менялись.
|
||||
const desktopLoadKeyRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!isDesktop || isSearchView) {
|
||||
desktopLoadKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (activeNav === "myads" || activeNav === "map") return;
|
||||
const q = searchQuery.trim();
|
||||
const key = `${q}|${feedFiltersKey}`;
|
||||
if (key === desktopLoadKeyRef.current) return;
|
||||
const timer = setTimeout(() => {
|
||||
desktopLoadKeyRef.current = key;
|
||||
feed.loadFeed(0, q, false, feedFilters);
|
||||
}, q ? 400 : 0);
|
||||
return () => clearTimeout(timer);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isDesktop, isSearchView, searchQuery, feedFiltersKey, activeNav]);
|
||||
|
||||
// Когда переключаемся на «Мои объявления» — подгружаем с бэкенда
|
||||
useEffect(() => {
|
||||
if (activeNav === "myads" && isAuthenticated && user?.id) {
|
||||
@@ -337,7 +383,7 @@ export default function MainFeed() {
|
||||
// Клик по локации на карточке — карта с фокусом на этом объявлении.
|
||||
//
|
||||
// Координаты берём из карточки, а если их там нет (объявление создано без
|
||||
// карты, либо лента отдаёт null) — догружаем их из /api/v1/posts/detail/{id}.
|
||||
// карты, либо лента отдаёт null) — догружаем их из /api/v1/posts/{id}.
|
||||
// Без этого карта открывалась на дефолтном центре Москвы: MapView получает
|
||||
// lat/lng из URL, а без них инициализируется на MAP_CENTER, и маркера
|
||||
// объявления в загруженных границах нет — фокус не к чему было привязать.
|
||||
@@ -350,9 +396,9 @@ export default function MainFeed() {
|
||||
|
||||
if (focusLat === null || focusLng === null) {
|
||||
try {
|
||||
// apiFetch, а не fetch: /detail/{id} владельцу отдаёт его собственные
|
||||
// apiFetch, а не fetch: /posts/{id} владельцу отдаёт его собственные
|
||||
// неопубликованные посты, а анонимному запросу бэкенд ответит 404.
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/detail/${ad.id}`);
|
||||
const res = await apiFetch(`${API_URL}/api/v1/posts/${ad.id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const detailLat = toCoordinate(data?.latitude);
|
||||
@@ -442,11 +488,27 @@ export default function MainFeed() {
|
||||
onReviewsClick={() => navigate("/reviews")}
|
||||
onCreatePost={handleCreatePost}
|
||||
onProfileClick={() => modals.open("profile")}
|
||||
onMapClick={handleMapClick}
|
||||
profileData={profileData}
|
||||
/>
|
||||
|
||||
<div className="f-main f-main-feed">
|
||||
{/* Шапка поиска: на мобильном сворачивается при скролле вниз (grid 1fr → 0fr) */}
|
||||
{isDesktop ? (!isMapView && (
|
||||
<DesktopFeedHeader
|
||||
activeNav={activeNav}
|
||||
typeFilter={typeFilter}
|
||||
onTypeFilterChange={setTypeFilter}
|
||||
searchQuery={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
cities={cities}
|
||||
selectedCities={selectedCities}
|
||||
onCitiesChange={setSelectedCities}
|
||||
count={filteredAds.length}
|
||||
loading={listLoading}
|
||||
onMapClick={handleMapClick}
|
||||
/>
|
||||
)) : (
|
||||
/* Шапка поиска: на мобильном сворачивается при скролле вниз (grid 1fr → 0fr) */
|
||||
<div className={`f-search-head${searchHeadHidden ? " is-hidden" : ""}`}>
|
||||
<div className="f-search-head-inner">
|
||||
{isSearchView && (
|
||||
@@ -471,9 +533,17 @@ export default function MainFeed() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="f-wrap">
|
||||
{isMapView ? (
|
||||
{isMapView && isDesktop ? (
|
||||
<DesktopMapView
|
||||
focusPostId={focusPostId}
|
||||
focusLat={focusLat}
|
||||
focusLng={focusLng}
|
||||
onPostClick={handleMapPostClick}
|
||||
/>
|
||||
) : isMapView ? (
|
||||
<MapView
|
||||
focusPostId={focusPostId}
|
||||
focusLat={focusLat}
|
||||
@@ -498,6 +568,26 @@ export default function MainFeed() {
|
||||
onRefresh={refreshCurrentList}
|
||||
disabled={isMapView || isSearchView || !["home", "items", "pets", "myads"].includes(activeNav)}
|
||||
/>
|
||||
{isDesktop ? (
|
||||
<div className="fd-grid">
|
||||
<FeedContent
|
||||
loading={listLoading}
|
||||
citySearchActive={selectedCities.length > 0}
|
||||
error={listError}
|
||||
filteredAds={filteredAds}
|
||||
activeNav={activeNav}
|
||||
searchPrompt={searchPrompt}
|
||||
showAds={showAds}
|
||||
onEdit={handleEdit}
|
||||
onDelete={actions.handleDelete}
|
||||
onMarkFound={actions.handleMarkFound}
|
||||
onReopen={actions.handleReopen}
|
||||
onLocationClick={handleLocationClick}
|
||||
onAuthRequired={() => modals.open("auth")}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<FeedContent
|
||||
loading={listLoading}
|
||||
citySearchActive={selectedCities.length > 0}
|
||||
@@ -514,6 +604,7 @@ export default function MainFeed() {
|
||||
onAuthRequired={() => modals.open("auth")}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
{infiniteFeed && !feed.loading && (
|
||||
<div ref={sentinelRef} style={{ height: "1px" }} />
|
||||
)}
|
||||
@@ -544,6 +635,11 @@ export default function MainFeed() {
|
||||
setSelectedCities([]);
|
||||
if (isMapView || isSearchView) navigate("/feed");
|
||||
}}
|
||||
onCreatePost={handleCreatePost}
|
||||
onMapClick={handleMapClick}
|
||||
onPostClick={(postId: number) => modals.open("postDetail", { postId })}
|
||||
onRulesClick={() => modals.open("rules")}
|
||||
onReviewsClick={() => navigate("/reviews")}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -570,6 +666,18 @@ export default function MainFeed() {
|
||||
|
||||
{modals.isOpen("rules") && <RulesModal onClose={modals.close} />}
|
||||
|
||||
{modals.isOpen("guide") && (
|
||||
<GuideModal
|
||||
onClose={modals.close}
|
||||
onLoginClick={isAuthenticated ? undefined : () => modals.open("auth")}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Гостю в ленте — подсказка «Ты здесь впервые?» со ссылкой на инструкцию */}
|
||||
{!isAuthenticated && !isMapView && (
|
||||
<GuestGuideBanner onOpenGuide={() => modals.open("guide")} />
|
||||
)}
|
||||
|
||||
{modals.isOpen("postDetail") && (
|
||||
<PostDetailModal
|
||||
postId={modals.modal.payload.postId}
|
||||
|
||||
@@ -5,6 +5,7 @@ import PhoneIcon from "../components/icons/PhoneIcon";
|
||||
import TrashIcon from "../components/icons/TrashIcon";
|
||||
import CheckIcon from "../components/icons/CheckIcon";
|
||||
import {useContactSeller} from "../hooks/useContactSeller";
|
||||
import {useRevealPhone} from "../hooks/useRevealPhone";
|
||||
import {useAuthContext} from "../context/AuthContext";
|
||||
import {getImageUrl} from "../config/authConstants";
|
||||
import {CATEGORY_PET} from "../config/feedConstants";
|
||||
@@ -15,7 +16,7 @@ import RewardPopup from "../components/feed/RewardPopup";
|
||||
import Toast from "../components/Toast";
|
||||
import {useTranslation} from 'react-i18next';
|
||||
|
||||
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact }) {
|
||||
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact, hideContact }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [showCalendar, setShowCalendar] = useState(false);
|
||||
const [showReward, setShowReward] = useState(false);
|
||||
@@ -31,6 +32,7 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
// isOwner тут не подходит — в общей ленте он false и для своих объявлений.
|
||||
const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id);
|
||||
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
|
||||
const phoneReveal = useRevealPhone(ad.id);
|
||||
|
||||
useEffect(() => {
|
||||
const check = () => {
|
||||
@@ -108,6 +110,19 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate})
|
||||
: foundText;
|
||||
|
||||
// Номер в ленту не приходит: в «Моих объявлениях» и в админке он есть в ad.phone,
|
||||
// в общей ленте его открывают кнопкой (proof-of-work на бэкенде) — и автор
|
||||
// своего объявления тоже, чтобы видеть то же, что покупатель.
|
||||
// У закрытого объявления номер не показывается: вещь уже вернулась.
|
||||
const shownPhone = ad.phone || phoneReveal.phone;
|
||||
// Объявление с контрольными вопросами: написать — только ответив на них, а номер
|
||||
// открывается заявителю после подтверждения ответов (в чате). Автор свой номер видит.
|
||||
// У потери это отсекает «нашёл, оплатите доставку», у находки — «это моё» по фото.
|
||||
const needsVerification = !isOwnAd
|
||||
&& Array.isArray(ad.verificationQuestions) && ad.verificationQuestions.length > 0;
|
||||
const canRevealPhone = !shownPhone && ad.phoneVisible && !isClosed && !needsVerification;
|
||||
const phoneAfterVerification = !shownPhone && ad.phoneVisible && !isClosed && needsVerification;
|
||||
|
||||
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
|
||||
|
||||
const typeBadge = (
|
||||
@@ -116,6 +131,34 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
</div>
|
||||
);
|
||||
|
||||
// У находки вознаграждения нет — его предлагает только владелец
|
||||
const hasReward = ad.reward && ad.type !== "found";
|
||||
// В ленте кнопка стоит в строке под описанием; в compact (объявление,
|
||||
// открытое с карты) этой строки нет — кнопка лежит на фото справа снизу,
|
||||
// чтобы её было видно сразу, без прокрутки окна.
|
||||
const rewardButton = hasReward && (
|
||||
<>
|
||||
<button
|
||||
ref={rewardAnchorRef}
|
||||
type="button"
|
||||
className={`f-card-reward-text f-card-reward-btn${compact ? " f-card-reward-on-img" : ""}`}
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
setShowReward(s => !s);
|
||||
}}
|
||||
>
|
||||
<span className="f-reward-btn-label">{t("postCard.reward")}</span>
|
||||
</button>
|
||||
{showReward && (
|
||||
<RewardPopup
|
||||
text={ad.rewardText || t("postCard.reward")}
|
||||
anchorRef={rewardAnchorRef}
|
||||
onClose={() => setShowReward(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`f-card${isClosed ? ' f-card-closed' : ''}${ad.type === "found" ? ' f-card-found' : ' f-card-loss'}`}
|
||||
role="group"
|
||||
@@ -210,6 +253,7 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{compact && rewardButton}
|
||||
</div>
|
||||
|
||||
{!compact && (
|
||||
@@ -282,45 +326,50 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
|
||||
{!compact && (
|
||||
<div className="f-card-meta">
|
||||
{ad.reward && (
|
||||
<>
|
||||
<button
|
||||
ref={rewardAnchorRef}
|
||||
type="button"
|
||||
className="f-card-reward-text f-card-reward-btn"
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
setShowReward(s => !s);
|
||||
}}
|
||||
>
|
||||
<span className="f-reward-btn-label">{t("postCard.reward")}</span>
|
||||
</button>
|
||||
{showReward && (
|
||||
<RewardPopup
|
||||
text={ad.rewardText || t("postCard.reward")}
|
||||
anchorRef={rewardAnchorRef}
|
||||
onClose={() => setShowReward(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
{rewardButton}
|
||||
{needsVerification && !isClosed && (
|
||||
<span className="f-card-verify-pill" title={t('postCard.phoneAfterVerificationHint')}>
|
||||
🛡️ {t('postCard.verifiedClaims')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="f-card-foot">
|
||||
<div className="f-card-foot-left">
|
||||
{ad.phone && (
|
||||
<a className="f-card-phone" href={`tel:${ad.phone}`}
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<PhoneIcon/> {ad.phone}
|
||||
</a>
|
||||
{shownPhone ? (
|
||||
<div className="f-card-phone-wrap">
|
||||
<a className="f-card-phone" href={`tel:${shownPhone}`}
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<PhoneIcon/> {shownPhone}
|
||||
</a>
|
||||
{/* Номер открыл не автор — напоминаем о главной схеме мошенников */}
|
||||
{!ad.phone && <span className="f-card-phone-hint">{t('postCard.phoneSafetyHint')}</span>}
|
||||
</div>
|
||||
) : phoneAfterVerification ? (
|
||||
<span className="f-card-phone f-card-phone-locked" title={t('postCard.phoneAfterVerificationHint')}>
|
||||
<PhoneIcon/> {t('postCard.phoneAfterVerification')}
|
||||
</span>
|
||||
) : canRevealPhone && (
|
||||
<button type="button" className="f-card-phone f-card-phone-reveal"
|
||||
disabled={phoneReveal.loading}
|
||||
aria-busy={phoneReveal.loading}
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
phoneReveal.reveal();
|
||||
}}>
|
||||
<PhoneIcon/> {phoneReveal.loading ? t('postCard.phoneChecking') : t('postCard.showPhone')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="f-card-foot-right">
|
||||
{!isOwnAd && (
|
||||
{isOwnAd ? (
|
||||
<span className="f-card-own-label">{t('postCard.ownAd')}</span>
|
||||
) : !hideContact && (
|
||||
<button type="button" className="f-card-contact"
|
||||
onClick={handleContact}>
|
||||
{t('postCard.write')}
|
||||
{!needsVerification ? t('postCard.write')
|
||||
: ad.type === "found" ? t('postCard.claimItem') : t('postCard.claimFound')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -361,6 +410,14 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phoneReveal.error && (
|
||||
<Toast
|
||||
message={phoneReveal.error}
|
||||
type="error"
|
||||
onDismiss={phoneReveal.clearError}
|
||||
/>
|
||||
)}
|
||||
|
||||
{contactError && (
|
||||
<Toast
|
||||
message={contactError}
|
||||
|
||||
95
src/pages/PostOnFeed.phone.test.jsx
Normal file
95
src/pages/PostOnFeed.phone.test.jsx
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Номер в карточке: в ленту он не приходит, открывается кнопкой
|
||||
* «Показать номер» (proof-of-work на бэкенде). Автор и админ видят номер сразу.
|
||||
*/
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import PostOnFeed from "./PostOnFeed";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { revealPhone } from "../api/phoneApi";
|
||||
import "../i18n";
|
||||
|
||||
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||||
jest.mock("../hooks/useContactSeller", () => ({
|
||||
useContactSeller: () => ({ contactSeller: jest.fn(), error: "", clearError: jest.fn() }),
|
||||
}));
|
||||
jest.mock("../api/phoneApi", () => ({ revealPhone: jest.fn() }));
|
||||
|
||||
const AD = { id: 7, userId: 2, title: "Ключи", type: "loss", status: "ACTIVE", images: [] };
|
||||
const SHOW = /Показать номер|Show number/;
|
||||
|
||||
beforeEach(() => {
|
||||
useAuthContext.mockReturnValue({ isAuthenticated: false, user: null });
|
||||
});
|
||||
|
||||
test("номер открывается по кнопке", async () => {
|
||||
revealPhone.mockResolvedValue("+7 (999) 111-22-33");
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
|
||||
|
||||
fireEvent.click(screen.getByText(SHOW));
|
||||
|
||||
expect(await screen.findByText("+7 (999) 111-22-33")).toBeTruthy();
|
||||
expect(revealPhone).toHaveBeenCalledWith(7, expect.anything());
|
||||
});
|
||||
|
||||
test("без согласия автора кнопки нет — только чат", () => {
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: false }} />);
|
||||
|
||||
expect(screen.queryByText(SHOW)).toBeNull();
|
||||
});
|
||||
|
||||
test("у закрытого объявления номер не предлагается", () => {
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true, status: "CLOSED" }} />);
|
||||
|
||||
expect(screen.queryByText(SHOW)).toBeNull();
|
||||
});
|
||||
|
||||
test("номер, пришедший с объявлением (автор, админ), показывается сразу", () => {
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true, phone: "+7 (900) 000-00-00" }} />);
|
||||
|
||||
expect(screen.getByText("+7 (900) 000-00-00")).toBeTruthy();
|
||||
expect(revealPhone).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("ошибка показа номера — сообщение", async () => {
|
||||
revealPhone.mockRejectedValue(new TypeError("Failed to fetch"));
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
|
||||
|
||||
fireEvent.click(screen.getByText(SHOW));
|
||||
|
||||
expect(await screen.findByText(/связ|connection|network/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("своё объявление в ленте: номер открывается кнопкой, вместо «Написать» — подпись", async () => {
|
||||
useAuthContext.mockReturnValue({ isAuthenticated: true, user: { id: 2 } });
|
||||
revealPhone.mockResolvedValue("+7 (999) 111-22-33");
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true }} />);
|
||||
|
||||
expect(screen.queryByText(/^(Написать|Write)$/)).toBeNull();
|
||||
expect(screen.getByText(/Ваше объявление|Your listing/)).toBeTruthy();
|
||||
fireEvent.click(screen.getByText(SHOW));
|
||||
expect(await screen.findByText("+7 (999) 111-22-33")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("находка с контрольными вопросами: вместо номера — «после проверки», кнопка «Это моё»", () => {
|
||||
useAuthContext.mockReturnValue({ isAuthenticated: true, user: { id: 5 } });
|
||||
render(<PostOnFeed ad={{ ...AD, type: "found", phoneVisible: true, verificationQuestions: ["Что на брелке?"] }} />);
|
||||
|
||||
expect(screen.queryByText(SHOW)).toBeNull();
|
||||
expect(screen.getByText(/Номер — после проверки|Number after check/)).toBeTruthy();
|
||||
expect(screen.getByText(/^(Это моё|It's mine)$/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("потеря с вопросами: нашедший пишет через «Я нашёл», номер — после проверки", () => {
|
||||
useAuthContext.mockReturnValue({ isAuthenticated: true, user: { id: 5 } });
|
||||
render(<PostOnFeed ad={{ ...AD, phoneVisible: true, verificationQuestions: ["Что выгравировано?"] }} />);
|
||||
|
||||
expect(screen.queryByText(SHOW)).toBeNull();
|
||||
expect(screen.getByText(/^(Я нашёл|I found it)$/)).toBeTruthy();
|
||||
});
|
||||
|
||||
test("автор своей находки с вопросами открывает номер как обычно", () => {
|
||||
useAuthContext.mockReturnValue({ isAuthenticated: true, user: { id: 2 } });
|
||||
render(<PostOnFeed ad={{ ...AD, type: "found", phoneVisible: true, verificationQuestions: ["Что на брелке?"] }} />);
|
||||
|
||||
expect(screen.getByText(SHOW)).toBeTruthy();
|
||||
});
|
||||
@@ -15,12 +15,14 @@ import { useReviews } from "../hooks/useReviews";
|
||||
import "../styles/reviews.css";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProfile } from "../hooks/useProfile";
|
||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||
|
||||
export default function ReviewsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { user, isAuthenticated, updateUser } = useAuthContext();
|
||||
const { fetchProfile } = useProfile();
|
||||
const isDesktop = useIsDesktop();
|
||||
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
const [profileModalOpen, setProfileModalOpen] = useState(false);
|
||||
@@ -88,16 +90,25 @@ export default function ReviewsPage() {
|
||||
open={sidebarOpen}
|
||||
activeNav="reviews"
|
||||
onClose={() => setSidebarOpen(false)}
|
||||
onNavClick={(key) => navigate("/feed")}
|
||||
onNavClick={(key) => navigate("/feed", isDesktop ? { state: { desktopNav: key } } : undefined)}
|
||||
isAuthenticated={isAuthenticated}
|
||||
onLoginClick={() => setAuthModalOpen(true)}
|
||||
onRulesClick={() => setRulesModalOpen(true)}
|
||||
onCreatePost={() => navigate("/feed")}
|
||||
onCreatePost={() => navigate("/feed", isDesktop ? { state: { desktopAction: "create" } } : undefined)}
|
||||
onMapClick={() => navigate("/feed?view=map")}
|
||||
onProfileClick={() => setProfileModalOpen(true)}
|
||||
profileData={profileData}
|
||||
/>
|
||||
|
||||
<div className="f-main">
|
||||
{isDesktop ? (
|
||||
<header className="fd-feed-header fd-page-header">
|
||||
<div className="fd-feed-header-inner">
|
||||
<h1 className="fd-feed-title">{t('reviews.title')}</h1>
|
||||
<p className="fd-feed-sub">{t('desktop.reviewsSub')}</p>
|
||||
</div>
|
||||
</header>
|
||||
) : (
|
||||
<AppTopBar
|
||||
onMenuClick={() => setSidebarOpen((v) => !v)}
|
||||
isAuthenticated={isAuthenticated}
|
||||
@@ -108,6 +119,7 @@ export default function ReviewsPage() {
|
||||
centerContent={<h1 className="rv-page-title">{t('reviews.title')}</h1>}
|
||||
hideWordmark
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="rv-scroll" ref={scrollRef}>
|
||||
<PullToRefresh containerRef={scrollRef} onRefresh={refreshReviews} disabled={loading} />
|
||||
|
||||
@@ -51,6 +51,12 @@ export function cachePostsFromChats(chats) {
|
||||
for (const chat of chats) {
|
||||
if (chat.post) {
|
||||
postByChatId.set(key(chat.id), chat.post);
|
||||
} else if (chat.postId != null) {
|
||||
// Объявление удалено: бэкенд оставил postId, но краткой карточки нет.
|
||||
// Сохраняем то, что знали о нём раньше (заголовок, фото), и помечаем removed,
|
||||
// чтобы в списке и шапке было понятно, о какой вещи был чат.
|
||||
const prev = postByChatId.get(key(chat.id));
|
||||
postByChatId.set(key(chat.id), { ...prev, id: chat.postId, removed: true });
|
||||
}
|
||||
}
|
||||
if (chats.length) persist();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,400;9..144,500;9..144,600;9..144,700&family=Inter:wght@400;500;600;700&display=swap');
|
||||
/* Шрифты (Literata, Inter) подключаются в public/index.html */
|
||||
|
||||
/*
|
||||
Design tokens live scoped to .nk-page so nothing outside this page
|
||||
@@ -301,7 +301,7 @@
|
||||
}
|
||||
|
||||
.nk-h1 {
|
||||
font-family: 'Fraunces', serif;
|
||||
font-family: 'Literata', serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(28px, 4.5vw, 56px);
|
||||
line-height: 1.06;
|
||||
@@ -378,7 +378,7 @@
|
||||
/* ---------- Steps (kept in sync in case re-enabled) ---------- */
|
||||
|
||||
.nk-h2 {
|
||||
font-family: 'Fraunces', serif;
|
||||
font-family: 'Literata', serif;
|
||||
font-size: clamp(24px, 3vw, 34px);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
@@ -410,7 +410,7 @@
|
||||
}
|
||||
|
||||
.nk-step-num {
|
||||
font-family: 'Fraunces', serif;
|
||||
font-family: 'Literata', serif;
|
||||
font-size: 15px;
|
||||
color: var(--nk-signal);
|
||||
font-weight: 600;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800;900&display=swap');
|
||||
/* Шрифты подключаются без блокировки рендера в public/index.html */
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
|
||||
@@ -215,6 +215,23 @@ button.f-card-reward-btn:focus-visible {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
/* Та же кнопка поверх фото (объявление, открытое с карты). Под ней может
|
||||
оказаться любое изображение, поэтому подложка — тёмное матовое стекло:
|
||||
золотой текст читается и на светлом, и на тёмном фото в обеих темах. */
|
||||
button.f-card-reward-btn.f-card-reward-on-img {
|
||||
position: absolute; right: 12px; bottom: 12px; z-index: 3;
|
||||
padding: 6px 14px;
|
||||
background: rgba(20, 16, 6, .62);
|
||||
border-color: rgba(230, 184, 0, .75);
|
||||
backdrop-filter: blur(8px) saturate(140%);
|
||||
-webkit-backdrop-filter: blur(8px) saturate(140%);
|
||||
box-shadow: 0 4px 14px rgba(0, 0, 0, .3), 0 0 14px rgba(230, 184, 0, .25);
|
||||
}
|
||||
button.f-card-reward-btn.f-card-reward-on-img:hover {
|
||||
background: rgba(20, 16, 6, .72);
|
||||
}
|
||||
.f-card-reward-on-img .f-reward-btn-label { font-size: .8rem; }
|
||||
|
||||
/* ── Всплывающее окно вознаграждения ── */
|
||||
.f-reward-popup {
|
||||
max-width: 260px;
|
||||
@@ -368,6 +385,12 @@ button.f-card-reward-btn:focus-visible {
|
||||
text-decoration: none; display: flex; align-items: center; gap: 4px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.f-card-phone-reveal {
|
||||
background: none; border: none; padding: 0;
|
||||
cursor: pointer; font-family: var(--font);
|
||||
}
|
||||
.f-card-own-label { color: var(--muted2); font-size: .8rem; font-weight: 600; }
|
||||
.f-card-phone-reveal:disabled { opacity: .6; cursor: progress; }
|
||||
.f-card-date { color: var(--muted2); font-size: .75rem; }
|
||||
|
||||
.f-card-contact {
|
||||
@@ -711,3 +734,16 @@ button.f-card-reward-btn:focus-visible {
|
||||
.fs-ad-sound:hover {
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
}
|
||||
|
||||
/* Находка с контрольными вопросами: номер — после проверки ответов */
|
||||
.f-card-verify-pill {
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
border-radius: 999px; padding: 3px 10px;
|
||||
font-size: .74rem; font-weight: 600;
|
||||
color: #1f9d55;
|
||||
background: rgba(31, 157, 85, .1);
|
||||
border: 1px solid rgba(31, 157, 85, .3);
|
||||
}
|
||||
.f-card-phone-locked { color: var(--muted); font-weight: 600; cursor: help; }
|
||||
.f-card-phone-wrap { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.f-card-phone-hint { color: var(--muted); font-size: .7rem; white-space: normal; }
|
||||
|
||||
@@ -122,10 +122,113 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.chat-header-title {
|
||||
flex: 1;
|
||||
color: var(--text-primary);
|
||||
font-weight: 800;
|
||||
font-size: 1rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
/* Аватар + заголовок объявления; с onInfo — кнопка, открывающая карточку */
|
||||
.chat-header-post {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
button.chat-header-post { cursor: pointer; }
|
||||
button.chat-header-post:hover .chat-header-title { text-decoration: underline; }
|
||||
.chat-header-text {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
.chat-header-meta { margin-top: 2px; }
|
||||
.chat-header-info-btn {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.chat-header-info-btn:hover {
|
||||
background: var(--hover-bg);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* Подпись объявления чата: тип, город, статус — различает похожие чаты */
|
||||
.chat-post-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 2px;
|
||||
min-width: 0;
|
||||
font-size: .7rem;
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
.chat-post-tag {
|
||||
flex-shrink: 0;
|
||||
border-radius: 999px;
|
||||
padding: 1px 7px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.chat-post-tag--loss { background: rgba(237,73,86,.1); color: #ed4956; }
|
||||
.chat-post-tag--found { background: rgba(48,168,94,.1); color: #30a85e; }
|
||||
.chat-post-tag--closed,
|
||||
.chat-post-tag--removed { background: var(--bg-input); color: var(--muted); }
|
||||
.chat-post-city {
|
||||
color: var(--muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Модалка объявления, открытая из чата */
|
||||
.chat-post-modal-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 12px 16px 16px;
|
||||
}
|
||||
.chat-post-open-btn {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-input);
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
font-size: .85rem;
|
||||
padding: 9px 18px;
|
||||
cursor: pointer;
|
||||
transition: background .15s;
|
||||
}
|
||||
.chat-post-open-btn:hover { background: var(--hover-bg); }
|
||||
.f-post-detail-gone {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
}
|
||||
.f-post-detail-gone-title {
|
||||
color: var(--text-primary);
|
||||
font-weight: 800;
|
||||
}
|
||||
.f-post-detail-gone-text {
|
||||
color: var(--muted);
|
||||
font-size: .9rem;
|
||||
}
|
||||
|
||||
.chat-header-avatar {
|
||||
@@ -248,6 +351,206 @@
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
/* ── Фото в сообщениях ── */
|
||||
.chat-bubble.has-photos {
|
||||
padding: 4px;
|
||||
width: min(300px, 70%);
|
||||
}
|
||||
.chat-bubble.has-photos .chat-bubble-text { padding: 6px 10px 0; }
|
||||
.chat-bubble.has-photos .chat-bubble-time { padding: 0 8px 4px; }
|
||||
.chat-photos {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 3px;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.chat-photos--single { grid-template-columns: 1fr; }
|
||||
.chat-photo {
|
||||
display: block;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: var(--bg-input);
|
||||
aspect-ratio: 1;
|
||||
cursor: zoom-in;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Одно фото — в своих пропорциях (из width/height), но не выше экрана */
|
||||
.chat-photos--single .chat-photo { aspect-ratio: 4 / 3; max-height: 60vh; }
|
||||
.chat-photo img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
/* ── Видео в сообщениях ── */
|
||||
.chat-video {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-height: 60vh;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
}
|
||||
.chat-video + .chat-photos { margin-top: 3px; }
|
||||
.chat-video video {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
background: #000;
|
||||
}
|
||||
.chat-video-duration {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, .6);
|
||||
color: #fff;
|
||||
font-size: .72rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
.chat-video--pending,
|
||||
.chat-video--failed {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
background: var(--bg-input);
|
||||
color: var(--muted);
|
||||
font-size: .82rem;
|
||||
text-align: center;
|
||||
padding: 12px;
|
||||
}
|
||||
.chat-bubble.mine .chat-video--pending,
|
||||
.chat-bubble.mine .chat-video--failed { background: rgba(255, 255, 255, .18); color: #fff; }
|
||||
|
||||
/* ── Выбор фото перед отправкой ── */
|
||||
.chat-attach-btn {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-input);
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.chat-attach-btn:hover:not(:disabled) { background: var(--hover-bg); color: var(--text-primary); }
|
||||
.chat-attach-btn:disabled { opacity: .4; cursor: default; }
|
||||
.chat-attach-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 16px 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.chat-attach-thumb {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.chat-attach-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.chat-attach-thumb.is-sending { opacity: .5; }
|
||||
.chat-attach-thumb--video { width: 96px; background: #000; }
|
||||
.chat-attach-thumb video { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.chat-attach-duration {
|
||||
position: absolute;
|
||||
left: 4px;
|
||||
bottom: 4px;
|
||||
padding: 1px 5px;
|
||||
border-radius: 6px;
|
||||
background: rgba(0, 0, 0, .6);
|
||||
color: #fff;
|
||||
font-size: .68rem;
|
||||
}
|
||||
.chat-attach-progress {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, .45);
|
||||
color: #fff;
|
||||
font-weight: 800;
|
||||
font-size: .85rem;
|
||||
}
|
||||
.chat-attach-thumb--video.is-sending { opacity: 1; }
|
||||
.chat-attach-thumb--busy { display: flex; align-items: center; justify-content: center; }
|
||||
.chat-attach-remove {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
right: 3px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: rgba(0, 0, 0, .6);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-attach-remove svg { width: 12px; height: 12px; }
|
||||
.chat-attach-error { color: var(--err); font-size: .8rem; }
|
||||
|
||||
/* ── Просмотр фото ── */
|
||||
.chat-viewer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, .92);
|
||||
}
|
||||
.chat-viewer-img {
|
||||
max-width: 100vw;
|
||||
max-height: 100vh;
|
||||
object-fit: contain;
|
||||
user-select: none;
|
||||
}
|
||||
.chat-viewer-close,
|
||||
.chat-viewer-nav {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, .14);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-viewer-close { top: calc(16px + env(safe-area-inset-top)); right: 16px; width: 40px; height: 40px; }
|
||||
.chat-viewer-nav { top: 50%; transform: translateY(-50%); width: 44px; height: 44px; font-size: 1.8rem; line-height: 1; }
|
||||
.chat-viewer-prev { left: 16px; }
|
||||
.chat-viewer-next { right: 16px; }
|
||||
.chat-viewer-close:hover,
|
||||
.chat-viewer-nav:hover { background: rgba(255, 255, 255, .26); }
|
||||
.chat-viewer-counter {
|
||||
position: absolute;
|
||||
bottom: calc(20px + env(safe-area-inset-bottom));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
color: #fff;
|
||||
font-size: .85rem;
|
||||
opacity: .8;
|
||||
}
|
||||
|
||||
/* ── Chat List ── */
|
||||
.chat-list {
|
||||
flex: 1;
|
||||
@@ -393,6 +696,8 @@
|
||||
.chat-bubble {
|
||||
max-width: 85%;
|
||||
}
|
||||
.chat-bubble.has-photos { width: min(280px, 85%); }
|
||||
.chat-attach-strip { padding: 8px 12px 0; }
|
||||
.chat-list {
|
||||
padding: 6px 10px;
|
||||
}
|
||||
@@ -425,3 +730,111 @@
|
||||
padding-bottom: calc(8px + env(safe-area-inset-bottom));
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Антифрод: предупреждения и заявки на находку ── */
|
||||
.chat-safety {
|
||||
align-self: stretch;
|
||||
border: 1px solid rgba(230, 150, 0, .35);
|
||||
background: rgba(255, 176, 32, .1);
|
||||
border-radius: 14px;
|
||||
padding: 10px 12px;
|
||||
font-size: .82rem;
|
||||
line-height: 1.4;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.chat-safety-main { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.chat-safety-icon { font-size: 1.1rem; line-height: 1.2; }
|
||||
.chat-safety-body { flex: 1; min-width: 0; }
|
||||
.chat-safety-title { font-weight: 700; margin-bottom: 2px; }
|
||||
.chat-safety-text { color: var(--muted); }
|
||||
.chat-safety-hide {
|
||||
background: none; border: none; padding: 0;
|
||||
color: var(--teal); font: inherit; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
.chat-safety-new { font-weight: 600; color: #c77700; }
|
||||
.chat-safety-main + .chat-safety-new { margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(230, 150, 0, .25); }
|
||||
|
||||
.chat-fraud-warning {
|
||||
margin-top: 6px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 10px;
|
||||
background: rgba(237, 73, 86, .1);
|
||||
color: var(--err);
|
||||
font-size: .8rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.chat-system {
|
||||
align-self: center;
|
||||
max-width: 85%;
|
||||
text-align: center;
|
||||
font-size: .8rem;
|
||||
color: var(--muted);
|
||||
background: var(--bg-input);
|
||||
border-radius: 999px;
|
||||
padding: 6px 14px;
|
||||
}
|
||||
.chat-system--approved { color: #1f9d55; background: rgba(31, 157, 85, .1); }
|
||||
.chat-system--rejected { color: var(--err); background: rgba(237, 73, 86, .08); }
|
||||
.chat-system-time { margin-left: 8px; font-size: .68rem; opacity: .7; }
|
||||
|
||||
.chat-bubble--claim { min-width: min(260px, 70%); }
|
||||
.chat-claim-card-title { font-weight: 700; margin-bottom: 6px; }
|
||||
.chat-claim-qa + .chat-claim-qa { margin-top: 8px; }
|
||||
.chat-claim-q { font-size: .8rem; opacity: .75; }
|
||||
.chat-claim-a { white-space: pre-wrap; }
|
||||
|
||||
.chat-claim-form {
|
||||
align-self: stretch;
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
background: var(--bg-surface-solid);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
padding: 14px;
|
||||
}
|
||||
.chat-claim-title { font-weight: 700; font-size: 1rem; }
|
||||
.chat-claim-intro { margin: 0; color: var(--muted); font-size: .85rem; line-height: 1.4; }
|
||||
.chat-claim-field { display: flex; flex-direction: column; gap: 6px; }
|
||||
.chat-claim-question { font-weight: 600; font-size: .9rem; }
|
||||
.chat-claim-answer { resize: vertical; min-height: 44px; font-family: var(--font); }
|
||||
.chat-claim-submit {
|
||||
align-self: flex-end;
|
||||
background: var(--teal); color: #fff; border: none;
|
||||
border-radius: 999px; padding: 10px 22px;
|
||||
font: inherit; font-weight: 700; cursor: pointer;
|
||||
}
|
||||
.chat-claim-submit:disabled { opacity: .45; cursor: default; }
|
||||
|
||||
.chat-verify {
|
||||
margin: 0 12px 8px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 14px;
|
||||
font-size: .85rem;
|
||||
line-height: 1.4;
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px;
|
||||
background: var(--bg-surface-solid);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.chat-input-area--locked .chat-verify { margin-top: 8px; margin-bottom: 12px; }
|
||||
.chat-verify > span { flex: 1 1 220px; }
|
||||
.chat-verify--pending { border-color: rgba(230, 150, 0, .4); }
|
||||
.chat-verify--rejected { border-color: rgba(237, 73, 86, .4); color: var(--err); }
|
||||
.chat-verify--approved { border-color: rgba(31, 157, 85, .4); }
|
||||
.chat-verify--owner { border-color: rgba(var(--teal-rgb), .4); }
|
||||
.chat-verify-actions { display: flex; gap: 8px; margin-left: auto; }
|
||||
.chat-verify-btn {
|
||||
border-radius: 999px; padding: 7px 16px;
|
||||
font: inherit; font-weight: 700; cursor: pointer;
|
||||
}
|
||||
.chat-verify-btn:disabled { opacity: .5; cursor: progress; }
|
||||
.chat-verify-btn--approve { background: var(--teal); color: #fff; border: 1px solid var(--teal); }
|
||||
.chat-verify-btn--reject { background: none; color: var(--err); border: 1px solid rgba(237, 73, 86, .5); }
|
||||
.chat-verify-phone {
|
||||
display: inline-flex; align-items: center; gap: 4px;
|
||||
background: none; border: none; padding: 0;
|
||||
color: var(--teal); font: inherit; font-weight: 700;
|
||||
text-decoration: none; cursor: pointer;
|
||||
}
|
||||
.chat-verify-phone:disabled { opacity: .6; cursor: progress; }
|
||||
|
||||
1061
src/styles/desktop.css
Normal file
1061
src/styles/desktop.css
Normal file
File diff suppressed because it is too large
Load Diff
274
src/styles/guide.css
Normal file
274
src/styles/guide.css
Normal file
@@ -0,0 +1,274 @@
|
||||
/* ── Инструкция (GuideModal) ── */
|
||||
.guide-modal {
|
||||
width: 520px;
|
||||
max-width: 96vw;
|
||||
}
|
||||
.guide-intro {
|
||||
margin: -8px 0 16px;
|
||||
color: var(--muted);
|
||||
font-size: .88rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.guide-steps {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.guide-step {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
background: var(--bg-surface-solid);
|
||||
}
|
||||
.guide-step-icon {
|
||||
flex-shrink: 0;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.15rem;
|
||||
background: rgba(var(--teal-rgb), .1);
|
||||
}
|
||||
.guide-step-body { min-width: 0; }
|
||||
.guide-step-title {
|
||||
color: var(--text-primary);
|
||||
font-weight: 800;
|
||||
font-size: .93rem;
|
||||
}
|
||||
.guide-step-num { color: var(--teal); }
|
||||
.guide-step-text {
|
||||
margin-top: 3px;
|
||||
color: var(--muted);
|
||||
font-size: .84rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.guide-safety {
|
||||
margin-top: 14px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(237, 73, 86, .25);
|
||||
background: rgba(237, 73, 86, .06);
|
||||
}
|
||||
.guide-safety-title {
|
||||
color: var(--text-primary);
|
||||
font-weight: 800;
|
||||
font-size: .9rem;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.guide-safety ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
color: var(--muted);
|
||||
font-size: .83rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.guide-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
.guide-btn {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--hover-bg);
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-weight: 800;
|
||||
font-size: .88rem;
|
||||
cursor: pointer;
|
||||
transition: filter .15s, background .15s;
|
||||
}
|
||||
.guide-btn-primary {
|
||||
border-color: transparent;
|
||||
background: var(--teal);
|
||||
color: #fff;
|
||||
}
|
||||
.guide-btn:hover { filter: brightness(1.06); }
|
||||
@media (max-width: 600px) {
|
||||
.guide-actions { flex-direction: column-reverse; }
|
||||
}
|
||||
|
||||
/* ── Приветственная подсказка для гостя (GuestGuideBanner) ──
|
||||
Сверху по центру на телефоне (смахивается вверх), справа сверху на десктопе
|
||||
(закрывается крестиком). Не перекрывает модалки: z-index ниже .f-modal-bg. */
|
||||
.guest-banner {
|
||||
position: fixed;
|
||||
z-index: 90;
|
||||
top: calc(10px + env(safe-area-inset-top, 0px));
|
||||
left: 50%;
|
||||
width: min(520px, calc(100% - 24px));
|
||||
--banner-x: -50%;
|
||||
transform: translate(var(--banner-x), var(--banner-drag, 0px));
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 12px 12px 14px 14px;
|
||||
border-radius: 18px;
|
||||
border: 1px solid rgba(var(--teal-rgb), .25);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(var(--teal-rgb), .10), rgba(var(--teal-rgb), 0) 60%),
|
||||
var(--bg-card);
|
||||
box-shadow: 0 12px 32px rgba(0, 0, 0, .16), 0 2px 6px rgba(0, 0, 0, .06);
|
||||
/* backwards, а не both: после появления transform снова берётся из правила
|
||||
выше — иначе финальный кадр анимации перекрыл бы сдвиг при свайпе */
|
||||
animation: guestBannerIn .45s cubic-bezier(.2, .9, .3, 1.15) backwards;
|
||||
touch-action: pan-x;
|
||||
user-select: none;
|
||||
}
|
||||
.guest-banner.is-dragging { transition: none; }
|
||||
.guest-banner.is-settling { transition: transform .2s ease; }
|
||||
.guest-banner.is-leaving {
|
||||
animation: guestBannerOut .25s ease-in forwards;
|
||||
}
|
||||
@keyframes guestBannerIn {
|
||||
from { opacity: 0; transform: translate(var(--banner-x), -130%); }
|
||||
to { opacity: 1; transform: translate(var(--banner-x), 0); }
|
||||
}
|
||||
@keyframes guestBannerOut {
|
||||
from { opacity: 1; transform: translate(var(--banner-x), var(--banner-drag, 0px)); }
|
||||
to { opacity: 0; transform: translate(var(--banner-x), -140%); }
|
||||
}
|
||||
.guest-banner-icon {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.35rem;
|
||||
background: rgba(var(--teal-rgb), .14);
|
||||
}
|
||||
/* Машущая рука: несколько взмахов от запястья (transform-origin — у основания
|
||||
ладони), потом пауза; цикл 6 с, первый взмах — сразу после появления карточки */
|
||||
.guest-banner-wave {
|
||||
display: inline-block;
|
||||
line-height: 1;
|
||||
transform-origin: 70% 75%;
|
||||
animation: guestWave 6s ease-in-out .5s infinite;
|
||||
}
|
||||
@keyframes guestWave {
|
||||
0% { transform: rotate(0deg); }
|
||||
4% { transform: rotate(16deg); }
|
||||
8% { transform: rotate(-10deg); }
|
||||
12% { transform: rotate(16deg); }
|
||||
16% { transform: rotate(-6deg); }
|
||||
20% { transform: rotate(12deg); }
|
||||
25% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(0deg); }
|
||||
}
|
||||
/* Мягкая волна от иконки в такт взмаху — привлекает взгляд, но не мигает */
|
||||
.guest-banner-icon::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
border: 2px solid rgba(var(--teal-rgb), .45);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
animation: guestWaveRing 6s ease-out .5s infinite;
|
||||
}
|
||||
@keyframes guestWaveRing {
|
||||
0% { opacity: .9; transform: scale(1); }
|
||||
22% { opacity: 0; transform: scale(1.45); }
|
||||
100% { opacity: 0; transform: scale(1.45); }
|
||||
}
|
||||
.guest-banner-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.guest-banner-title {
|
||||
color: var(--text-primary);
|
||||
font-weight: 800;
|
||||
font-size: .95rem;
|
||||
}
|
||||
.guest-banner-text {
|
||||
margin-top: 2px;
|
||||
color: var(--muted);
|
||||
font-size: .83rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.guest-banner-btn {
|
||||
margin-top: 10px;
|
||||
padding: 8px 14px;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: var(--teal);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 800;
|
||||
font-size: .82rem;
|
||||
cursor: pointer;
|
||||
transition: filter .15s;
|
||||
}
|
||||
.guest-banner-btn:hover { filter: brightness(1.08); }
|
||||
.guest-banner-close {
|
||||
flex-shrink: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.guest-banner-close:hover { background: var(--hover-bg); color: var(--text-primary); }
|
||||
.guest-banner-close svg { width: 16px; height: 16px; }
|
||||
/* «Ручка» — подсказка, что карточку можно смахнуть вверх (только телефон) */
|
||||
.guest-banner-handle {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 5px;
|
||||
width: 36px;
|
||||
height: 4px;
|
||||
margin-left: -18px;
|
||||
border-radius: 2px;
|
||||
background: var(--muted2);
|
||||
}
|
||||
|
||||
/* Десктоп: правый нижний угол — сверху карточка закрывала бы «Карту» и поиск
|
||||
в шапке ленты. Появляется снизу, закрывается крестиком. */
|
||||
@media (min-width: 900px) {
|
||||
.guest-banner {
|
||||
top: auto;
|
||||
bottom: 24px;
|
||||
left: auto;
|
||||
right: 24px;
|
||||
width: 380px;
|
||||
--banner-x: 0px;
|
||||
padding-bottom: 12px;
|
||||
animation-name: guestBannerInDesktop;
|
||||
}
|
||||
.guest-banner.is-leaving { animation-name: guestBannerOutDesktop; }
|
||||
.guest-banner-handle { display: none; }
|
||||
}
|
||||
@keyframes guestBannerInDesktop {
|
||||
from { opacity: 0; transform: translateY(24px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes guestBannerOutDesktop {
|
||||
from { opacity: 1; transform: translateY(0); }
|
||||
to { opacity: 0; transform: translateY(16px); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.guest-banner,
|
||||
.guest-banner.is-leaving { animation-duration: .01ms; }
|
||||
.guest-banner-wave,
|
||||
.guest-banner-icon::after { animation: none; }
|
||||
}
|
||||
@@ -103,6 +103,40 @@ select.f-m-field::selection { background: transparent; }
|
||||
}
|
||||
.f-img-upload-label:hover { border-color: var(--teal); background: rgba(var(--teal-rgb), .05); color: var(--teal); }
|
||||
.f-img-input { display: none; }
|
||||
.f-img-upload-text {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 4px;
|
||||
text-align: center;
|
||||
}
|
||||
.f-img-upload-sub { font-size: .75rem; opacity: .8; }
|
||||
|
||||
/* Перетаскивание фото (десктоп): над зоной файл — пунктир окрашивается,
|
||||
поле подсвечивается и чуть «приподнимается», превью приглушаются,
|
||||
чтобы взгляд шёл на место, куда отпустить файл. */
|
||||
.f-img-drop-zone .f-img-upload-label {
|
||||
transition: border-color .2s, background .2s, color .2s, transform .2s, box-shadow .2s;
|
||||
}
|
||||
.f-img-drop-zone.is-dragover .f-img-upload-label {
|
||||
border-color: var(--teal);
|
||||
border-style: solid;
|
||||
background: rgba(var(--teal-rgb), .1);
|
||||
color: var(--teal);
|
||||
font-weight: 600;
|
||||
transform: scale(1.02);
|
||||
box-shadow: 0 0 0 4px rgba(var(--teal-rgb), .15);
|
||||
}
|
||||
.f-img-drop-zone.is-dragover .f-img-grid { opacity: .55; transition: opacity .2s; }
|
||||
/* Аватар уже есть: поверх превью — затемнение с подсказкой «заменить» */
|
||||
.f-img-drop-zone.is-dragover .f-img-preview-wrap {
|
||||
box-shadow: 0 0 0 3px var(--teal), 0 0 0 7px rgba(var(--teal-rgb), .18);
|
||||
}
|
||||
.f-img-drop-overlay {
|
||||
position: absolute; inset: 0; z-index: 1;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
padding: 8px; text-align: center;
|
||||
background: rgba(0, 0, 0, .55);
|
||||
color: #fff; font-size: .75rem; font-weight: 600; line-height: 1.3;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Profile Photo Preview */
|
||||
.f-img-preview-wrap {
|
||||
@@ -679,3 +713,21 @@ select.f-m-field::selection { background: transparent; }
|
||||
@keyframes f-addr-spin { to { transform: rotate(360deg); } }
|
||||
.f-map-open { margin-top: 10px; }
|
||||
.f-map-modal-frame.loading { opacity: .85; }
|
||||
|
||||
/* Контрольные вопросы находки в форме объявления */
|
||||
.f-verify-question + .f-verify-question { margin-top: 8px; }
|
||||
.f-verify-add {
|
||||
margin-top: 8px;
|
||||
background: none; border: none; padding: 0;
|
||||
color: var(--teal); font-family: var(--font); font-weight: 600; cursor: pointer;
|
||||
}
|
||||
|
||||
/* Предупреждение о мошенниках в форме объявления */
|
||||
.f-safety-note {
|
||||
border: 1px solid rgba(230, 150, 0, .35);
|
||||
background: rgba(255, 176, 32, .1);
|
||||
border-radius: 14px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.f-safety-title { font-weight: 700; font-size: .88rem; margin-bottom: 4px; }
|
||||
.f-safety-text { margin: 0; color: var(--muted); font-size: .82rem; line-height: 1.4; }
|
||||
|
||||
@@ -63,7 +63,11 @@ export function getChatDisplayInfo(chat, post, unreadMap, t) {
|
||||
const imgSrc = getImageUrl(post?.images?.[0]);
|
||||
const emoji = post?.emoji;
|
||||
const unreadCount = unreadMap[chat.id] ?? chat.unreadCount ?? chat.unreadMessages ?? 0;
|
||||
const preview = getLastMessageText(chat) || t('chat.noMessages');
|
||||
// У сообщения только с фото или видео текста нет — в превью пишем «Фото»/«Видео»
|
||||
const photoPreview = chat.lastMessageAttachments > 0
|
||||
? (chat.lastMessageAttachmentKind === "VIDEO" ? `🎬 ${t('chat.videoPreview')}` : `📷 ${t('chat.photoPreview')}`)
|
||||
: "";
|
||||
const preview = getLastMessageText(chat) || photoPreview || t('chat.noMessages');
|
||||
|
||||
return { title, imgSrc, emoji, unreadCount, preview };
|
||||
}
|
||||
@@ -18,9 +18,13 @@ export function escapeHtml(value) {
|
||||
/**
|
||||
* URL для CSS url('...') внутри HTML-атрибута style: кавычки, скобки и
|
||||
* обратный слэш процентно кодируются, чтобы значение не вышло за пределы url().
|
||||
*
|
||||
* В классе символов `\\` — это обратный слэш, а `\s` — пробельные символы.
|
||||
* Раньше там стояло `\\s`, то есть «слэш и буква s»: каждая s в URL
|
||||
* превращалась в %73 (https:// → http%73://), и фото в маркерах карты пропадали.
|
||||
*/
|
||||
export function escapeCssUrl(value) {
|
||||
return String(value ?? "").replace(/['"()\\s<>]/g, (ch) =>
|
||||
return String(value ?? "").replace(/['"()\\\s<>]/g, (ch) =>
|
||||
`%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`
|
||||
);
|
||||
}
|
||||
|
||||
109
src/utils/proofOfWork.js
Normal file
109
src/utils/proofOfWork.js
Normal file
@@ -0,0 +1,109 @@
|
||||
// src/utils/proofOfWork.js
|
||||
|
||||
/**
|
||||
* Решатель proof-of-work задачи для показа номера (схема ALTCHA, бэкенд —
|
||||
* ProofOfWorkService). Сервер присылает challenge = SHA-256(salt + n) и
|
||||
* maxNumber; ищем n перебором от 0 до maxNumber. В среднем это maxNumber/2
|
||||
* хешей — доли секунды для человека, часы CPU для сборщика тысяч номеров.
|
||||
*
|
||||
* SHA-256 написан на JS, а не через crypto.subtle: subtle есть только в
|
||||
* защищённом контексте (HTTPS/localhost) и на коротких строках медленнее
|
||||
* из-за промиса на каждый хеш. Перебор идёт порциями с уступкой потоку,
|
||||
* чтобы интерфейс не зависал.
|
||||
*/
|
||||
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const W = new Uint32Array(64);
|
||||
|
||||
/**
|
||||
* SHA-256 строки из ASCII-символов (salt — hex, цифры и точки) в виде 8 слов
|
||||
* со знаком (|0), чтобы сравнивать без перевода в hex.
|
||||
*/
|
||||
export function sha256Words(str) {
|
||||
const len = str.length;
|
||||
const blocks = ((len + 8) >> 6) + 1;
|
||||
const m = new Uint32Array(blocks * 16);
|
||||
for (let i = 0; i < len; i++) {
|
||||
m[i >> 2] |= (str.charCodeAt(i) & 0xff) << (24 - (i & 3) * 8);
|
||||
}
|
||||
m[len >> 2] |= 0x80 << (24 - (len & 3) * 8);
|
||||
m[blocks * 16 - 1] = len * 8;
|
||||
|
||||
let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
|
||||
let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
|
||||
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
for (let t = 0; t < 16; t++) W[t] = m[b * 16 + t];
|
||||
for (let t = 16; t < 64; t++) {
|
||||
const x = W[t - 15];
|
||||
const y = W[t - 2];
|
||||
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
||||
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
||||
W[t] = (W[t - 16] + s0 + W[t - 7] + s1) | 0;
|
||||
}
|
||||
let a = h0, bb = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
|
||||
for (let t = 0; t < 64; t++) {
|
||||
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
||||
const ch = (e & f) ^ (~e & g);
|
||||
const t1 = (h + S1 + ch + K[t] + W[t]) | 0;
|
||||
const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
||||
const maj = (a & bb) ^ (a & c) ^ (bb & c);
|
||||
const t2 = (S0 + maj) | 0;
|
||||
h = g; g = f; f = e; e = (d + t1) | 0;
|
||||
d = c; c = bb; bb = a; a = (t1 + t2) | 0;
|
||||
}
|
||||
h0 = (h0 + a) | 0; h1 = (h1 + bb) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0;
|
||||
h4 = (h4 + e) | 0; h5 = (h5 + f) | 0; h6 = (h6 + g) | 0; h7 = (h7 + h) | 0;
|
||||
}
|
||||
return [h0, h1, h2, h3, h4, h5, h6, h7];
|
||||
}
|
||||
|
||||
export function sha256Hex(str) {
|
||||
return sha256Words(str).map(w => (w >>> 0).toString(16).padStart(8, "0")).join("");
|
||||
}
|
||||
|
||||
function hexToWords(hex) {
|
||||
const words = [];
|
||||
for (let i = 0; i < 8; i++) words.push(parseInt(hex.slice(i * 8, i * 8 + 8), 16) | 0);
|
||||
return words;
|
||||
}
|
||||
|
||||
const yieldToBrowser = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
/**
|
||||
* Находит n, для которого SHA-256(salt + n) === challenge.
|
||||
*
|
||||
* @param {{algorithm: string, challenge: string, salt: string, maxNumber: number}} task
|
||||
* @param {{signal?: AbortSignal, chunk?: number}} [options]
|
||||
* @returns {Promise<number>}
|
||||
*/
|
||||
export async function solveChallenge(task, { signal, chunk = 20000 } = {}) {
|
||||
if (task.algorithm !== "SHA-256" || !/^[0-9a-f]{64}$/.test(task.challenge || "")) {
|
||||
throw new Error("Unsupported proof-of-work challenge");
|
||||
}
|
||||
const target = hexToWords(task.challenge);
|
||||
const { salt, maxNumber } = task;
|
||||
|
||||
for (let n = 0; n <= maxNumber; n++) {
|
||||
const h = sha256Words(salt + n);
|
||||
if (h[0] === target[0] && h[1] === target[1] && h[2] === target[2] && h[3] === target[3]
|
||||
&& h[4] === target[4] && h[5] === target[5] && h[6] === target[6] && h[7] === target[7]) {
|
||||
return n;
|
||||
}
|
||||
if (n % chunk === chunk - 1) {
|
||||
await yieldToBrowser();
|
||||
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
}
|
||||
}
|
||||
throw new Error("Proof-of-work solution not found");
|
||||
}
|
||||
34
src/utils/proofOfWork.test.js
Normal file
34
src/utils/proofOfWork.test.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import { createHash } from "crypto";
|
||||
import { sha256Hex, solveChallenge } from "./proofOfWork";
|
||||
|
||||
const nodeSha256 = (s) => createHash("sha256").update(s).digest("hex");
|
||||
|
||||
test("SHA-256 совпадает с эталоном", () => {
|
||||
expect(sha256Hex("abc")).toBe("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
expect(sha256Hex("")).toBe(nodeSha256(""));
|
||||
// строка длиннее одного блока (64 байта)
|
||||
const long = "a1b2c3d4e5f6a7b8c9d0e1f2.123456.1793102400".repeat(3);
|
||||
expect(sha256Hex(long)).toBe(nodeSha256(long));
|
||||
});
|
||||
|
||||
test("решает задачу в формате бэкенда (salt + n)", async () => {
|
||||
const salt = "0a1b2c3d4e5f60718293a4b5.42.1793102400";
|
||||
const secret = 31337;
|
||||
const task = { algorithm: "SHA-256", challenge: nodeSha256(salt + secret), salt, maxNumber: 50000 };
|
||||
|
||||
await expect(solveChallenge(task, { chunk: 5000 })).resolves.toBe(secret);
|
||||
});
|
||||
|
||||
test("неизвестный алгоритм не решается", async () => {
|
||||
await expect(solveChallenge({ algorithm: "MD5", challenge: "x", salt: "s", maxNumber: 1 }))
|
||||
.rejects.toThrow();
|
||||
});
|
||||
|
||||
test("перебор прерывается по AbortSignal", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const task = { algorithm: "SHA-256", challenge: "0".repeat(64), salt: "s", maxNumber: 100000 };
|
||||
|
||||
await expect(solveChallenge(task, { signal: controller.signal, chunk: 100 }))
|
||||
.rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
27
src/utils/relativeTime.js
Normal file
27
src/utils/relativeTime.js
Normal file
@@ -0,0 +1,27 @@
|
||||
const UNITS = [
|
||||
["year", 365 * 24 * 3600],
|
||||
["month", 30 * 24 * 3600],
|
||||
["week", 7 * 24 * 3600],
|
||||
["day", 24 * 3600],
|
||||
["hour", 3600],
|
||||
["minute", 60],
|
||||
];
|
||||
|
||||
/**
|
||||
* «5 минут назад», «вчера», «2 недели назад» — по языку интерфейса.
|
||||
* Возвращает null для пустой/некорректной даты.
|
||||
*/
|
||||
export function formatRelativeTime(value, language = "ru", now = Date.now()) {
|
||||
if (!value) return null;
|
||||
const time = new Date(value).getTime();
|
||||
if (!Number.isFinite(time)) return null;
|
||||
|
||||
const diffSec = Math.round((time - now) / 1000);
|
||||
const abs = Math.abs(diffSec);
|
||||
const rtf = new Intl.RelativeTimeFormat(language, { numeric: "auto" });
|
||||
|
||||
for (const [unit, sec] of UNITS) {
|
||||
if (abs >= sec) return rtf.format(Math.round(diffSec / sec), unit);
|
||||
}
|
||||
return rtf.format(0, "minute");
|
||||
}
|
||||
@@ -35,6 +35,15 @@ describe("escapeHtml", () => {
|
||||
it("URL не выходит за пределы url('...')", () => {
|
||||
expect(escapeCssUrl("a.jpg');background:url('x")).not.toMatch(/['()]/);
|
||||
});
|
||||
|
||||
it("обычный presigned URL не меняется (буква s не кодируется)", () => {
|
||||
const url = "https://s3.example.com/bucket/a.jpg?X-Amz-Signature=abc&presigned=true";
|
||||
expect(escapeCssUrl(url)).toBe(url);
|
||||
});
|
||||
|
||||
it("кодирует обратный слэш и пробельные символы", () => {
|
||||
expect(escapeCssUrl("a\\b c\nd")).toBe("a%5Cb%20c%0Ad");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePassword", () => {
|
||||
|
||||
@@ -12,10 +12,10 @@ export function validatePostForm(form) {
|
||||
if (!description) errors.description = i18n.t('validation.descriptionRequired');
|
||||
if (!form.category) errors.category = i18n.t('validation.categoryRequired');
|
||||
|
||||
// Телефон обязателен для объявления (в отличие от профиля) — проверяем
|
||||
// количество цифр, а не просто пустоту, т.к. form.phone форматируется
|
||||
// через formatPhone и всегда содержит минимум "+7".
|
||||
if ((form.phone ?? "").replace(/\D/g, "").length < 11) {
|
||||
// Телефон нужен, только если автор согласился его показывать (иначе
|
||||
// связь через чат). Проверяем количество цифр, а не пустоту: form.phone
|
||||
// форматируется через formatPhone и всегда содержит минимум "+7".
|
||||
if (form.phoneVisible && (form.phone ?? "").replace(/\D/g, "").length < 11) {
|
||||
errors.phone = i18n.t('validation.phoneRequired');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* public/index.html подключает API Яндекс.Карт через <script defer>,
|
||||
* public/index.html подключает API Яндекс.Карт через <script async>,
|
||||
* поэтому к моменту первого рендера window.ymaps может быть ещё undefined:
|
||||
* скрипт не скачался, медленный CDN, блокировщик рекламы, офлайн.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user