Compare commits

124 Commits

Author SHA1 Message Date
SlimusMinus
4d9e97b13c Merge pull request #130 from SlimusMinus/fix-openMap
All checks were successful
deploy-frontend / deploy (push) Successful in 53s
deploy-frontend-prod / deploy (push) Successful in 47s
fixed name on openMap
2026-12-02 00:44:36 +03:00
SlimusMinus
2d64428910 fixed name on openMap 2026-12-02 00:42:29 +03:00
SlimusMinus
b333e0855b Merge pull request #129 from SlimusMinus/add-prod_deploy
All checks were successful
deploy-frontend / deploy (push) Successful in 1m14s
deploy-frontend-prod / deploy (push) Successful in 1m8s
added deploy-prod.yml
2026-11-20 00:27:36 +03:00
SlimusMinus
89ceb2049f added deploy-prod.yml 2026-11-20 00:25:47 +03:00
SlimusMinus
4fccd5bf43 Merge pull request #128 from SlimusMinus/feat-anti_fraud
All checks were successful
deploy-frontend / deploy (push) Successful in 1m24s
Add verification questions, claim flow and scam warnings
2026-11-11 01:11:50 +03:00
SlimusMinus
3dd174afa5 Add verification questions, claim flow and scam warnings
- post form: up to 3 verification questions (loss and found) and a
  "how not to get scammed" note; sent as verificationQuestions JSON
- feed card: "I found it" / "It's mine" instead of "Write" for posts with
  questions; phone shows "after check" until the author approves
- chat draft shows ClaimForm; VerificationPanel lets the author approve or
  reject answers and locks the claimant's input until approval, then offers
  the author's phone
- messages: claim answers card, verification system line, fraudSignal
  warnings for the recipient; ChatSafetyNotice with new-account mark
- tests, README

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 01:04:55 +03:00
SlimusMinus
133becd255 Merge pull request #127 from SlimusMinus/feat-guest_guide
All checks were successful
deploy-frontend / deploy (push) Successful in 51s
Add first-visit tip and how-to guide for guests
2026-10-29 22:26:08 +03:00
SlimusMinus
df91e7e129 Add first-visit tip and how-to guide for guests
- guests in the feed see a "New here?" tip with a waving hand: swipe up to
  dismiss on mobile (top), close button on desktop (bottom right); shown
  once, remembered in localStorage
- GuideModal: six short steps (feed and map, map pins, posting, chat with
  photos/video, phone reveal, marking as returned) plus safety tips;
  guests get a sign-in button
- "How it works" item in the mobile menu and the desktop sidebar
- ru/en texts, tests, README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 22:25:15 +03:00
SlimusMinus
025ba2d637 Merge pull request #126 from SlimusMinus/docs-chat_media
All checks were successful
deploy-frontend / deploy (push) Successful in 51s
Document chat media, phone reveal and desktop layout in README
2026-10-29 21:47:19 +03:00
SlimusMinus
94af58b542 Document chat media, phone reveal and desktop layout in README
- chat: post info in header and list, photo and video attachments,
  viewer, /chats/new draft, new chat endpoints and WebSocket updates
- phone reveal via proof-of-work, phoneVisible consent, closedAt
- desktop layout components, new hooks, utils and styles
- fix outdated notes: compressImage, chat creation endpoint, backend branches

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 21:46:27 +03:00
SlimusMinus
427827a32b Merge pull request #125 from SlimusMinus/feat-chat_video
All checks were successful
deploy-frontend / deploy (push) Successful in 55s
Send and play videos in chats
2026-10-28 23:15:38 +03:00
SlimusMinus
b94ef2918c Send and play videos in chats
- the attach button accepts one video per message (MP4, MOV, WebM, 3GP);
  type, size (100 MB) and duration (60 s) are checked before upload
- the video is uploaded straight to storage with a progress indicator,
  then confirmed; the message shows "processing" until the server pushes
  the ready (or failed) version over WebSocket
- player with poster and duration in bubbles; fresh links when they expire
- chat list preview shows "Video" for video-only messages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:00:18 +03:00
SlimusMinus
0e3cac62a4 Merge pull request #124 from SlimusMinus/feat-chat_photos
All checks were successful
deploy-frontend / deploy (push) Successful in 56s
Send and view photos in chats
2026-10-28 22:29:41 +03:00
SlimusMinus
b7b30575a2 Send and view photos in chats
- paperclip button and clipboard paste in the chat input, previews with
  remove, up to 10 photos per message (sent via REST multipart)
- photos in message bubbles with reserved size, fullscreen viewer
  (arrows, swipe, Esc), fresh link when a presigned URL expires
- chat list preview shows "Photo" for photo-only messages
- keep the feed pinned to the bottom when the preview strip appears

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 22:26:44 +03:00
SlimusMinus
0380bc8985 Merge pull request #123 from SlimusMinus/feat-chat_post_info
All checks were successful
deploy-frontend / deploy (push) Successful in 56s
Show which listing each chat is about
2026-10-28 21:20:41 +03:00
SlimusMinus
33bd002f98 Show which listing each chat is about
The chat list and header show the listing's type, city and closed/deleted
status; the header info button opens the full listing in PostDetailModal
with a "show on map" action. Deleted or unpublished listings are marked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:17:58 +03:00
SlimusMinus
3811c5a133 Merge pull request #122 from SlimusMinus/fix-show_phone_number
All checks were successful
deploy-frontend / deploy (push) Successful in 55s
fixed show phone number
2026-10-27 22:54:20 +03:00
SlimusMinus
4b7db41a97 fixed show phone number 2026-10-27 22:52:10 +03:00
SlimusMinus
113355c0ef Merge pull request #121 from SlimusMinus/feat-profile_photo_dragdrop
All checks were successful
deploy-frontend / deploy (push) Successful in 47s
Desktop: drag and drop profile photo; share drop-zone hook with post …
2026-10-26 23:29:58 +03:00
SlimusMinus
16b886081b Desktop: drag and drop profile photo; share drop-zone hook with post form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:27:40 +03:00
SlimusMinus
abd6f83535 Merge pull request #120 from SlimusMinus/feat-profile_hide_email
Hide email field in profile edit modal
2026-10-26 23:22:31 +03:00
SlimusMinus
a2706944bd Hide email field in profile edit modal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:21:57 +03:00
SlimusMinus
532b5b45f3 Merge pull request #119 from SlimusMinus/feat-post_phone_from_profile
Prefill post phone from user profile
2026-10-26 23:13:27 +03:00
SlimusMinus
bb8f3263f8 Prefill post phone from user profile
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:01:47 +03:00
SlimusMinus
a8a0292535 Merge pull request #118 from SlimusMinus/feat-desktop_photo_dragdrop
Desktop: drag and drop photos into the post form
2026-10-26 22:53:43 +03:00
SlimusMinus
c0aaed7d28 Desktop: drag and drop photos into the post form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:51:53 +03:00
SlimusMinus
a657bd0762 Merge pull request #117 from SlimusMinus/feat-map_reward_button
All checks were successful
deploy-frontend / deploy (push) Successful in 49s
Show reward button on photo in posts opened from the map
2026-10-26 22:41:50 +03:00
SlimusMinus
3eec48d263 Show reward button on photo in posts opened from the map
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:38:32 +03:00
SlimusMinus
fc3e5be236 Merge pull request #116 from SlimusMinus/fix-desktop_post_modal_backdrop
Desktop: close post form only via the cross, not on backdrop click
2026-10-26 22:27:35 +03:00
SlimusMinus
83af2dda12 Desktop: close post form only via the cross, not on backdrop click
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:21:57 +03:00
SlimusMinus
833b735b4a Merge pull request #115 from SlimusMinus/feat-desktop_logo_feed
All checks were successful
deploy-frontend / deploy (push) Successful in 54s
Desktop sidebar: logo opens /feed, add About item linking to start page
2026-10-26 22:04:39 +03:00
SlimusMinus
ed4684c0ed Desktop sidebar: logo opens /feed, add About item linking to start page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:01:35 +03:00
SlimusMinus
d95167d3f3 Merge pull request #114 from SlimusMinus/fix-landing_cyrillic_font
Replace Fraunces with Literata in landing headings for Cyrillic support
2026-10-26 18:42:46 +03:00
SlimusMinus
ff59ce8ca6 Replace Fraunces with Literata in landing headings for Cyrillic support
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:40:39 +03:00
SlimusMinus
7ca4c99218 Merge pull request #113 from SlimusMinus/fix-found_hide_reward
Hide reward for FOUND posts in feed card and post form
2026-10-26 18:36:59 +03:00
SlimusMinus
04a5c2e66c Hide reward for FOUND posts in feed card and post form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:33:19 +03:00
SlimusMinus
645005a5d0 Merge pull request #112 from SlimusMinus/desktop-redesign
All checks were successful
deploy-frontend / deploy (push) Successful in 2m2s
fixed desktop version
2026-10-23 00:05:40 +03:00
SlimusMinus
140a31982a fixed desktop version 2026-10-23 00:02:44 +03:00
SlimusMinus
83ae74636b Merge pull request #111 from SlimusMinus/fix_email
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
fixed email
2026-10-21 23:08:54 +03:00
SlimusMinus
45220b9bda fixed email 2026-10-21 23:06:34 +03:00
SlimusMinus
e36165b5b1 Merge pull request #110 from SlimusMinus/fix-map_marker_images
All checks were successful
deploy-frontend / deploy (push) Successful in 45s
Fix map marker photos: escapeCssUrl no longer encodes the letter "s"
2026-10-21 22:54:46 +03:00
SlimusMinus
bfc9a1bd1d Fix map marker photos: escapeCssUrl no longer encodes the letter "s"
The character class /['"()\s<>]/ matched a backslash and the letter "s"
instead of whitespace, so every "s" in a marker image URL became %73
(https:// -> http%73://). The colored circles still rendered, but the
background-image URL was broken. Use \\s (backslash + whitespace).

Add tests: escapeCssUrl keeps a presigned URL intact and still encodes
backslash/whitespace; MapView puts the original imageUrl into the marker
template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:51:36 +03:00
SlimusMinus
f25d034cad Merge pull request #109 from SlimusMinus/ci-github_actions
All checks were successful
deploy-frontend / deploy (push) Successful in 1m59s
Add GitHub Actions CI: lint, typecheck, tests and build on PRs to master
2026-10-21 22:32:49 +03:00
SlimusMinus
5cd2fe70a4 Add GitHub Actions CI: lint, typecheck, tests and build on PRs to master
Runs on every pull request to master and on push to master (Node 22,
npm ci, CI=true). The gitea deploy workflow is unchanged. README
describes the check and recommends making it required for master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:27:35 +03:00
SlimusMinus
e1d539a9d5 Merge pull request #108 from SlimusMinus/fix-posts_api_stage2
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
Posts API stage 2: one post at /posts/{id}, no legacy user-posts fall…
2026-10-21 00:10:12 +03:00
SlimusMinus
ec713f3da1 Posts API stage 2: one post at /posts/{id}, no legacy user-posts fallback
- Post detail and map focus load GET /api/v1/posts/{id}
- My posts use only GET /api/v1/users/{id}/posts
- README: requires the stage 2 backend (deploy backend first)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:05:20 +03:00
SlimusMinus
d09c2c71ce Merge pull request #107 from SlimusMinus/fix-fonts_loading
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
Load Google Fonts and Yandex Maps without blocking app start
2026-10-20 23:46:20 +03:00
SlimusMinus
2af5f4acb9 Load Google Fonts and Yandex Maps without blocking app start
The fonts were pulled by @import inside the main CSS bundle; the deferred app
bundle waited for that stylesheet, so a slow fonts.googleapis.com kept the page
blank for 20-30 s. Fonts now load from index.html as a print stylesheet switched
on by onload (text renders with a fallback font meanwhile, display=swap).

The Maps API script was defer, so the app bundle (deferred after it) could not
run until the Maps API downloaded. It is async now; map code already waits for
window.ymaps via whenYmapsReady.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:44:50 +03:00
SlimusMinus
d53174a1cf Merge pull request #106 from SlimusMinus/add-chat_errors
All checks were successful
deploy-frontend / deploy (push) Successful in 45s
added chat error
2026-10-20 23:26:33 +03:00
SlimusMinus
86442b8c93 added chat error 2026-10-20 23:25:26 +03:00
SlimusMinus
ba919c015e Merge pull request #105 from SlimusMinus/fix-front_review
All checks were successful
deploy-frontend / deploy (push) Successful in 2m0s
Fix front review
2026-10-20 22:56:28 +03:00
SlimusMinus
8618db6a88 Reviews: readable submit errors (400 text, 429)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:56:58 +03:00
SlimusMinus
a029254cf0 Tests for auth refresh, ad viewability and URL safety; nginx, Dockerfile, README
- Jest: single-flight refresh, session expiry vs transient errors, token save on login change,
  logout revoke, IAB viewability, safe URLs, HTML escaping, password policy, ad session id
- test:ci with explicit testMatch (dot-directories in worktree paths hid all tests)
- nginx: gzip, nosniff/Referrer-Policy/X-Frame-Options, no-cache for index.html
- Dockerfile: npm ci, REACT_APP_WS_ERROR_QUEUE build arg
- README: new backend contracts, flags, compatibility notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:56:39 +03:00
SlimusMinus
804018d2ce Campaign stats in admin, user posts via new route, safer ad creation
- Admin: campaign stats panel (impressions, clicks, CTR per campaign and ad) with date range
- My posts: GET /api/v1/users/{id}/posts with paging, fallback to the legacy route
- Ad creation: retry after a failed video upload reuses the created ad; show backend 400 text
- Fullscreen ad form: only absolute http(s) target URLs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:53:08 +03:00
SlimusMinus
db37befb8d Support new backend contracts: single-flight refresh, ad impression tokens, error handling
- apiFetch: proactive refresh, cross-tab single-flight via Web Locks, no logout on transient errors
- AuthContext: save tokens returned on own login change, revoke refresh on logout, sync tabs
- Ads: X-Session-Id, impressionToken in impression/click, IAB viewability, safe http(s) targetUrl
- STOMP: refresh before CONNECT, stop reconnect loop on dead session, /user/queue/errors behind flag
- Auth form: password 8 chars / 72 bytes; 429/413 messages via describeApiError
- My posts with auth + moderation badges; post form step validation and field limits
- Map: escape user text in Yandex hint/template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:03:42 +03:00
SlimusMinus
67de963d6d Merge pull request #104 from SlimusMinus/change-main_icon
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
changed main icon
2026-10-19 01:43:10 +03:00
SlimusMinus
46a6770e4a changed main icon 2026-10-19 01:42:36 +03:00
SlimusMinus
ca6bea2b60 Merge pull request #103 from SlimusMinus/fix-review_top_bar
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
moved word review on review page
2026-10-19 01:34:00 +03:00
SlimusMinus
c334dab4a2 moved word review on review page 2026-10-19 01:33:26 +03:00
SlimusMinus
374faba349 Merge pull request #102 from SlimusMinus/fix-advert_slot
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
fixed empty advertising slot
2026-10-19 01:24:38 +03:00
SlimusMinus
80a5b641ce fixed empty advertising slot 2026-10-19 01:24:03 +03:00
SlimusMinus
3ac8d35a27 Merge pull request #101 from SlimusMinus/add-review_load
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
added review load
2026-10-19 01:11:37 +03:00
SlimusMinus
a8b4375bd1 added review load 2026-10-19 01:11:03 +03:00
SlimusMinus
95b2d7a58a Merge pull request #100 from SlimusMinus/fix-city_search
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
del add unknown city
2026-10-19 00:37:14 +03:00
SlimusMinus
838443fcb2 del add unknown city 2026-10-19 00:36:41 +03:00
SlimusMinus
11bc782e39 Merge pull request #99 from SlimusMinus/fix-city
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
fixed city search
2026-10-19 00:19:27 +03:00
SlimusMinus
28fedb4308 fixed city search 2026-10-19 00:18:49 +03:00
SlimusMinus
0c9af11063 Merge pull request #98 from SlimusMinus/full-text-search
All checks were successful
deploy-frontend / deploy (push) Successful in 54s
fixed search and add hints
2026-10-18 23:50:34 +03:00
SlimusMinus
49ba7f737a fixed search and add hints 2026-10-18 23:49:56 +03:00
SlimusMinus
36bc4e0c21 Merge pull request #97 from SlimusMinus/fix-compress_image
All checks were successful
deploy-frontend / deploy (push) Successful in 46s
fixed compress image
2026-10-15 01:29:45 +03:00
SlimusMinus
f75df406ce fixed compress image 2026-10-15 01:29:07 +03:00
SlimusMinus
c56f2bcdb1 Merge pull request #96 from SlimusMinus/pin_calendar
All checks were successful
deploy-frontend / deploy (push) Successful in 46s
pinned the calendar
2026-10-15 01:05:42 +03:00
SlimusMinus
67f0b9c488 pinned the calendar 2026-10-15 01:05:01 +03:00
SlimusMinus
219d08aba4 Merge pull request #95 from SlimusMinus/change-post_map
All checks were successful
deploy-frontend / deploy (push) Successful in 47s
changed address on city on post
2026-10-15 00:30:49 +03:00
SlimusMinus
b6d6df88b3 changed address on city on post 2026-10-15 00:27:46 +03:00
SlimusMinus
19fbbf6d63 Merge pull request #94 from SlimusMinus/fix-missing-geo-files
All checks were successful
deploy-frontend / deploy (push) Successful in 56s
add missing AddressAutocomplete and yandexGeo files
2026-10-15 00:10:06 +03:00
SlimusMinus
23e692afe8 add missing AddressAutocomplete and yandexGeo files
They are imported by CreateUpdatePost.jsx and useYandexMap.js but were left
out of d3f4ae0, which broke the Docker build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 00:09:21 +03:00
SlimusMinus
0145c252f4 Merge pull request #93 from SlimusMinus/add-hints_map
Some checks failed
deploy-frontend / deploy (push) Failing after 14s
added hints on map
2026-10-15 00:00:32 +03:00
SlimusMinus
d3f4ae085d added hints on map 2026-10-14 23:59:45 +03:00
SlimusMinus
2c72d6020e Merge pull request #92 from SlimusMinus/fix-chat_page
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
added blur for chat
2026-10-14 02:06:54 +03:00
SlimusMinus
289695a244 added blur for chat 2026-10-14 02:06:20 +03:00
SlimusMinus
4c27de1ca5 Merge pull request #91 from SlimusMinus/chat-wallpaper
All checks were successful
deploy-frontend / deploy (push) Successful in 46s
fixed chat wallpaper
2026-10-14 01:35:28 +03:00
SlimusMinus
d71a4cc1bd fixed chat wallpaper 2026-10-14 01:34:34 +03:00
SlimusMinus
6a0b033265 Merge pull request #90 from SlimusMinus/chat-on-first-message
All checks were successful
deploy-frontend / deploy (push) Successful in 51s
open a draft chat and create it on the first message
2026-10-13 01:49:33 +03:00
SlimusMinus
08f3a7e2bb open a draft chat and create it on the first message
"Написать" now looks up an existing chat for the ad (GET, never creates).
If there is none it opens /chats/new as a draft with the ad in the header;
the first send calls POST /chats/with/{userId}/messages, which creates the
chat with that message, and the page switches to /chats/{id}. Reloading
/chats/new without draft data goes back to the chat list.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:45:21 +03:00
SlimusMinus
e26283f907 Merge pull request #89 from SlimusMinus/fix-chat-post-image
All checks were successful
deploy-frontend / deploy (push) Successful in 44s
Fix chat post image
2026-10-13 01:34:30 +03:00
SlimusMinus
46f546c293 hide "write" button on own ads, log chat creation errors
The feed card showed the contact button on the user's own ads (isOwner is
false in the main feed), and the backend rejects a chat with yourself
with 400. The button is now hidden when ad.userId is the current user,
and createOrGetChat logs the backend error message.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:31:36 +03:00
SlimusMinus
5c48067842 fix chat list image taken from the clicked card instead of the chat
createOrGetChat stored the clicked card's post for the returned chat id,
even when the backend returned an existing chat about another ad. The
chat then showed the new ad's image until the next list fetch replaced
it with the real one. The backend's chat.post is now the source of truth;
card data only adds the emoji for the same ad.

Also limit the chat input to 4000 characters, matching the backend.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:23:12 +03:00
SlimusMinus
a122d4871a Merge pull request #88 from SlimusMinus/fix-feed-first-load
All checks were successful
deploy-frontend / deploy (push) Successful in 49s
fix feed first load losing page 0
2026-10-13 01:10:34 +03:00
SlimusMinus
8208c9f4d8 fix feed first load losing page 0
The infinite-scroll sentinel is visible on the first render (empty list,
loading=false) and could request page 1 before page 0 was loaded. Its
newer requestId made the page 0 response stale, so the feed showed only
the second page. Append requests are now ignored until the first page has
loaded and while a page 0 reload is in flight.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:07:26 +03:00
SlimusMinus
db6889c9db Merge pull request #87 from SlimusMinus/fix-get_image
All checks were successful
deploy-frontend / deploy (push) Successful in 51s
fixed get image url
2026-10-13 00:45:28 +03:00
SlimusMinus
2cc3237370 fixed get image url 2026-10-13 00:44:49 +03:00
SlimusMinus
0fce7f1536 Merge pull request #86 from SlimusMinus/add-page_scroll
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
added scroll on items and pets
2026-10-12 00:46:20 +03:00
SlimusMinus
fea07d505a added scroll on items and pets 2026-10-12 00:45:48 +03:00
SlimusMinus
03a0d2ebce Merge pull request #85 from SlimusMinus/fix_btn_nahodka_logo
All checks were successful
deploy-frontend / deploy (push) Successful in 41s
fixed push on button NakhodkaLanding on sideBar
2026-10-12 00:28:33 +03:00
SlimusMinus
89fdef31cc fixed push on button NakhodkaLanding on sideBar 2026-10-12 00:27:48 +03:00
SlimusMinus
16a55c95c0 Merge pull request #84 from SlimusMinus/fix-post_image_color
All checks were successful
deploy-frontend / deploy (push) Successful in 45s
fixed color facets of the image
2026-10-12 00:10:32 +03:00
SlimusMinus
2fd28ee776 fixed color facets of the image 2026-10-12 00:09:51 +03:00
SlimusMinus
597169407e Merge pull request #83 from SlimusMinus/add-timezone
All checks were successful
deploy-frontend / deploy (push) Successful in 1m52s
added timezone and fix chat
2026-10-11 23:30:12 +03:00
SlimusMinus
1aeda90da1 added timezone and fix chat 2026-10-11 23:29:27 +03:00
SlimusMinus
93f00e2cb4 Merge pull request #82 from SlimusMinus/add-carousel
All checks were successful
deploy-frontend / deploy (push) Successful in 43s
added carousel image on post on mainFeed
2026-10-09 01:21:47 +03:00
SlimusMinus
b924483231 added carousel image on post on mainFeed 2026-10-09 01:21:14 +03:00
SlimusMinus
55c71e664d Merge pull request #81 from SlimusMinus/fix-image_feed
All checks were successful
deploy-frontend / deploy (push) Successful in 45s
fixed image on post on mainFeed
2026-10-09 01:00:53 +03:00
SlimusMinus
326d00d005 fixed image on post on mainFeed 2026-10-09 01:00:21 +03:00
SlimusMinus
17795e71ad Merge pull request #80 from SlimusMinus/fix-chat_bucket
All checks were successful
deploy-frontend / deploy (push) Successful in 46s
fixed chat bucket
2026-10-09 00:43:55 +03:00
SlimusMinus
17ad88e59f fixed chat bucket 2026-10-09 00:43:12 +03:00
SlimusMinus
13a91b3f74 Merge pull request #79 from SlimusMinus/fix-main_filter
All checks were successful
deploy-frontend / deploy (push) Successful in 46s
fixed mainLogo filter
2026-10-09 00:23:51 +03:00
SlimusMinus
77a873a78c fixed mainLogo filter 2026-10-09 00:23:16 +03:00
SlimusMinus
259bf51fdf Merge pull request #78 from SlimusMinus/go-to-server
go-to-server
2026-10-08 23:47:01 +03:00
SlimusMinus
b97387b159 Fix home name
All checks were successful
deploy-frontend / deploy (push) Successful in 11s
2026-10-08 00:27:51 +03:00
SlimusMinus
9d38a77904 Test auto deploy
All checks were successful
deploy-frontend / deploy (push) Successful in 45s
2026-10-07 23:37:02 +03:00
SlimusMinus
1d3c5bcf0f Add Docker build and deploy pipeline
All checks were successful
deploy-frontend / deploy (push) Successful in 1m58s
2026-10-07 23:31:51 +03:00
SlimusMinus
bfbe84c9aa Add Docker build and deploy pipeline
Some checks failed
deploy-frontend / deploy (push) Failing after 5s
2026-10-07 23:29:38 +03:00
SlimusMinus
6dc61050d9 Add Docker build and deploy pipeline
Some checks failed
deploy-frontend / deploy (push) Failing after 11s
2026-10-07 23:27:38 +03:00
SlimusMinus
6791ee6eb3 Merge pull request #77 from SlimusMinus/add-reject_post
added rejected posts for admin
2026-10-06 02:07:55 +03:00
SlimusMinus
0074e51829 added rejected posts for admin 2026-10-06 02:06:44 +03:00
SlimusMinus
9ccad319cd Merge pull request #76 from SlimusMinus/fix-lan_lat_post
fixed lan and lon on post
2026-10-06 01:25:37 +03:00
SlimusMinus
bd3f997677 fixed lan and lon on post 2026-10-06 01:24:28 +03:00
SlimusMinus
3cfe389144 Merge pull request #75 from SlimusMinus/fix-all_code
fix bug and errors
2026-10-06 01:00:50 +03:00
SlimusMinus
d94a6782a4 fix bug and errors 2026-10-06 01:00:10 +03:00
SlimusMinus
73e3634ec4 Merge pull request #74 from SlimusMinus/fix-admin_panel
added all feeds for admin
2026-10-02 01:51:26 +03:00
SlimusMinus
841bf091d4 added all feeds for admin 2026-10-02 01:50:42 +03:00
SlimusMinus
510bfc06f2 Merge pull request #73 from SlimusMinus/added-box_map
fixed map by redis
2026-09-29 01:07:43 +03:00
SlimusMinus
a4a9f955d8 fixed map by redis 2026-09-29 01:06:59 +03:00
185 changed files with 13225 additions and 4144 deletions

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
.git
node_modules
build
.idea

3
.env
View File

@@ -1,3 +0,0 @@
REACT_APP_YANDEX_GEOCODER_KEY=c2d3c717-a109-4494-8863-7edbc32044e3
REACT_APP_YANDEX_MAPS_KEY=d4696cc8-6a1f-4356-9219-108ac474093b
REACT_APP_API_URL=http://192.168.1.75:8080

25
.env.example Normal file
View File

@@ -0,0 +1,25 @@
# Скопируйте этот файл в .env и подставьте свои значения.
# .env в .gitignore не попадает — реальные ключи не должны попадать в репозиторий.
# URL бэкенда. В dev чаще всего http://localhost:8080
REACT_APP_API_URL=http://localhost:8080
# Ключ Яндекс.Геокодера (обратное геокодирование адреса в координаты).
# Получить: https://developer.tech.yandex.ru/
REACT_APP_YANDEX_GEOCODER_KEY=
# Публичный ключ Яндекс.Карт (подставляется в public/index.html при загрузке API-карт).
# Получить: https://developer.tech.yandex.ru/
REACT_APP_YANDEX_MAPS_KEY=
# Почта поддержки в модалке «Поддержка». Необязательно — есть значение по умолчанию.
REACT_APP_SUPPORT_EMAIL=
# Необязательно: ключ «API Геосаджеста» Яндекса — подсказки адреса как на Яндекс Картах.
# Без него подсказки берутся из Геокодера (REACT_APP_YANDEX_GEOCODER_KEY).
# Получить: https://developer.tech.yandex.ru/
REACT_APP_YANDEX_SUGGEST_KEY=
# true — подписка на /user/queue/errors (ошибки отправки сообщений чата).
# Включать только после деплоя нового бэкенда: старый отклоняет подписку и рвёт WebSocket.
REACT_APP_WS_ERROR_QUEUE=false

View 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

View File

@@ -0,0 +1,27 @@
name: deploy-frontend
on:
push:
branches: [main]
jobs:
deploy:
runs-on: host
steps:
- uses: actions/checkout@v4
- name: Build image
env:
GEOCODER_KEY: ${{ secrets.REACT_APP_YANDEX_GEOCODER_KEY }}
MAPS_KEY: ${{ secrets.REACT_APP_YANDEX_MAPS_KEY }}
SUGGEST_KEY: ${{ secrets.REACT_APP_YANDEX_SUGGEST_KEY }}
run: |
docker build \
--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
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d frontend
- name: Cleanup
run: docker image prune -f

34
.github/workflows/ci.yml vendored Normal file
View 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

4
.gitignore vendored
View File

@@ -13,6 +13,10 @@
# misc
.DS_Store
# env — реальные ключи и адреса бэкенда не коммитим.
# Образец переменных держим в .env.example
.env
.env.local
.env.development.local
.env.test.local

9
.npmrc Normal file
View File

@@ -0,0 +1,9 @@
# react-scripts@5.0.1 объявляет typescript как ОПЦИОНАЛЬНЫЙ peer с диапазоном
# "^3.2.1 || ^4", а проекту нужен TypeScript 5.x: на TS 4 не собираются
# @types/react 18.3 и zod v4 (269 ошибок в node_modules).
#
# Конфликт чисто формальный: react-scripts типы не проверяет, их вырезает babel,
# а tsc запускается отдельно через `npm run typecheck`. Поэтому разрешаем
# npm игнорировать peer-диапазоны и не заставлять каждого нового разработчика
# ставить зависимости через --force / --legacy-peer-deps вручную.
legacy-peer-deps=true

22
Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json .npmrc ./
# npm ci — ровно версии из package-lock.json (legacy-peer-deps берётся из .npmrc)
RUN npm ci
COPY . .
ARG REACT_APP_API_URL=https://app.nahodka-test.online
ARG REACT_APP_YANDEX_GEOCODER_KEY=
ARG REACT_APP_YANDEX_MAPS_KEY=
ARG REACT_APP_YANDEX_SUGGEST_KEY=
ENV REACT_APP_API_URL=$REACT_APP_API_URL
ENV REACT_APP_YANDEX_GEOCODER_KEY=$REACT_APP_YANDEX_GEOCODER_KEY
ENV REACT_APP_YANDEX_MAPS_KEY=$REACT_APP_YANDEX_MAPS_KEY
ENV REACT_APP_YANDEX_SUGGEST_KEY=$REACT_APP_YANDEX_SUGGEST_KEY
# true — после деплоя бэкенда, принимающего подписку /user/queue/errors
ARG REACT_APP_WS_ERROR_QUEUE=false
ENV REACT_APP_WS_ERROR_QUEUE=$REACT_APP_WS_ERROR_QUEUE
RUN npm run build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/build /usr/share/nginx/html

791
README.md
View File

@@ -1,70 +1,785 @@
# Getting Started with Create React App
# Находка
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
Платформа для поиска потерянных вещей и питомцев. SPA на React 18 с JWT-аутентификацией
и автоматическим обновлением токена, чатом на WebSocket (STOMP/SockJS) с фото и видео,
картами Яндекса, загрузкой изображений, защитой номера телефона от сбора, админ-панелью
рекламы и модерации объявлений, i18n (ru/en), светлой/тёмной темой и отдельной
десктопной раскладкой (от 900 px).
## Available Scripts
---
In the project directory, you can run:
## Содержание
### `npm start`
1. [Быстрый старт](#1-быстрый-старт)
2. [Переменные окружения](#2-переменные-окружения)
3. [Стек и зависимости](#3-стек-и-зависимости)
4. [Скрипты](#4-скрипты)
5. [Структура проекта](#5-структура-проекта)
6. [Маршруты](#6-маршруты)
7. [Ключевые компоненты](#7-ключевые-компоненты)
8. [Контексты](#8-контексты)
9. [Хуки](#9-хуки)
10. [API-эндпоинты](#10-api-эндпоинты)
11. [WebSocket](#11-websocket)
12. [Админские эндпоинты](#12-админские-эндпоинты)
13. [Стили и темы](#13-стили-и-темы)
14. [Основные сценарии](#14-основные-сценарии)
15. [Известные проблемы и предупреждения](#15-известные-проблемы-и-предупреждения)
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
---
The page will reload when you make changes.\
You may also see any lint errors in the console.
## 1. Быстрый старт
### `npm test`
Требуется Node.js 18+ (проверено на Node 24).
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
```bash
npm install # зависимости (см. раздел о .npmrc)
npm start # dev-сервер на http://localhost:3000
npm run build # production-сборка в build/
```
### `npm run build`
Фронтенд ожидает работающий бэкенд (по умолчанию `http://localhost:8080`).
Если нужно обращаться к другому адресу — скопируйте `.env.example` в `.env`
и задайте `REACT_APP_API_URL`.
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
---
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
## 2. Переменные окружения
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
Файл `.env` **не** коммитится (см. `.gitignore`), шаблон — `.env.example`.
### `npm run eject`
| Переменная | Обязательна | По умолчанию | Описание |
|------------|-------------|--------------|----------|
| `REACT_APP_API_URL` | да | `http://localhost:8080` | Базовый URL бэкенда |
| `REACT_APP_YANDEX_GEOCODER_KEY` | для карты | — | Яндекс.Геокодер: обратное геокодирование координат → адрес |
| `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` (ошибки отправки сообщений чата). Бэкенд из `master` эту подписку поддерживает; со старым бэкендом (до backend-review) не включать — он отклоняет подписку и закрывает STOMP-соединение |
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
> **Безопасность.** Ключи Яндекса — публичные, но попадание реального `.env` в git
> означает утечку в историю коммитов. Если файл уже коммитился, перевыпустите ключи:
> добавление `.env` в `.gitignore` не удаляет его из истории.
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
---
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
## 3. Стек и зависимости
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
| Пакет | Назначение |
|-------|-----------|
| `react` / `react-dom` 18 | UI |
| `react-router-dom` 7 | Роутинг (`BrowserRouter`) |
| `@stomp/stompjs` + `sockjs-client` | WebSocket (STOMP) для чата и непрочитанных |
| `framer-motion` | Анимации модалок и переходов |
| `react-hook-form` + `@hookform/resolvers` + `zod` 4 | Формы и их валидация |
| `i18next` + `react-i18next` | Локализация ru/en |
| `@emoji-mart/react` + `@emoji-mart/data` + `emoji-mart` | Эмодзи-пикер в чате |
| `react-scripts` 5.0.1 | Сборка/дев-сервер (CRA) |
## Learn More
Карты Яндекса подключаются напрямую через глобальный `window.ymaps`
(см. `src/utils/ymapsApi.js`), без обёртки — она ждёт готовности API
с таймаутом и отдаёт ошибку вместо вечного спиннера.
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
Dev-зависимости: `typescript` 5.9, `@types/react` 18, `@types/react-dom`,
`@types/node`, `@testing-library/*`.
To learn React, check out the [React documentation](https://reactjs.org/).
### `.npmrc` и конфликт peer-зависимостей
### Code Splitting
В репозитории лежит `.npmrc` с `legacy-peer-deps=true`. Причина: `react-scripts@5.0.1`
объявляет `typescript` **опциональным** peer-диапазоном `^3.2.1 || ^4`, а проекту нужен
TypeScript 5 (на TS 4 не собираются `@types/react` 18.3 и `zod` 4). Конфликт формальный:
CRA типы не проверяет — их вырезает babel, а проверка запускается отдельно через
`npm run typecheck`.
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
Побочный эффект `legacy-peer-deps`: npm не ставит peer-зависимости автоматически,
поэтому `emoji-mart` объявлен в `dependencies` явно (его требует `@emoji-mart/react`).
### Analyzing the Bundle Size
---
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
## 4. Скрипты
### Making a Progressive Web App
| Скрипт | Что делает |
|--------|-----------|
| `npm start` | Dev-сервер с hot reload |
| `npm run build` | Production-сборка в `build/` |
| `npm test` | Jest в watch-режиме |
| `npm run test:ci` | Тесты один раз (`--watchAll=false`) — для CI. `--testMatch` задан явно: в путях с каталогом-точкой (`.claude/worktrees/...`) стандартный шаблон CRA не находит ни одного теста |
| `npm run lint` | ESLint по `src`, `--max-warnings=0` |
| `npm run typecheck` | `tsc --noEmit` по `tsconfig.json` |
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
Перед коммитом стоит прогнать все четыре проверки: `lint`, `typecheck`, `test:ci`, `build`.
### Advanced Configuration
### CI (GitHub Actions)
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
`.github/workflows/ci.yml` запускается на каждый PR в `master` и на push в `master`:
Node 22, `npm ci`, затем те же четыре проверки с `CI=true` (в этом режиме
предупреждения сборки CRA считаются ошибками). `REACT_APP_*` не задаются — для
проверок они не нужны. Деплой по-прежнему делает `.gitea/workflows/deploy.yml`.
### Deployment
Рекомендуется включить защиту ветки: GitHub → Settings → Branches → правило для
`master` → *Require status checks to pass before merging* → выбрать проверку
`lint, typecheck, test, build` (появится в списке после первого запуска workflow).
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
---
### `npm run build` fails to minify
## 5. Структура проекта
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
```
src/
├── index.js # Точка входа
├── App.js # Провайдеры + маршруты
├── i18n.js # Инициализация i18next, persist языка
├── legacy.d.ts # Типы ассетов (*.css, *.png, ...)
│
├── api/
│ ├── apiClient.jsx # apiFetch: Authorization + refresh токена по 401
│ ├── adminAdsApi.js # Кампании, реклама, фуллскрин-реклама
│ ├── adminContentApi.js # Админские объявления: список, статус, удаление
│ ├── adsApi.js # Фуллскрин-реклама, presigned-выгрузка видео
│ ├── apiErrors.js # ApiError, readApiError, describeApiError
│ ├── phoneApi.js # Показ номера: задача proof-of-work → номер
│ └── searchApi.js # Подсказки поиска
│
├── config/
│ ├── authConstants.js # API_URL
│ ├── feedConstants.js # Пункты меню, категории, пустая форма
│ └── landingConstants.js # Контент лендинга
│
├── context/
│ ├── AuthContext.jsx # user, token, isAuthenticated, isAdmin, login/logout
│ ├── ThemeContext.jsx # Светлая/тёмная тема
│ └── UnreadContext.jsx # Счётчики непрочитанных чатов
│
├── stores/
│ ├── activeChatStore.js # Активный чат
│ └── chatPostStore.js # Кэш «объявление ↔ чат» (localStorage); удалённое объявление помечается removed
│
├── hooks/ # см. раздел 9
│
├── utils/
│ ├── adSession.js # ID рекламной сессии (устойчив к запрету localStorage)
│ ├── campaignStatus.js # Статусы кампаний
│ ├── 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/
│ ├── NakhodkaLanding.jsx # Лендинг «/»
│ ├── MainFeed.tsx # Лента объявлений — главная страница
│ ├── MapModal.jsx, MapView.jsx # Карта и полноэкранный режим
│ ├── ChatListPage.jsx, ChatPage.jsx
│ ├── ReviewsPage.jsx
│ ├── CreateUpdatePost.jsx # Создание/редактирование (в т.ч. adminMode)
│ ├── PostOnFeed.jsx # Карточка объявления
│ ├── RulesModal.jsx, SupportModal.jsx
│ └── AdminAdsPage.jsx # Админ-панель
│
├── components/
│ ├── feed/ FeedTopBar.tsx, FeedContent, FeedSearchBar, PullToRefresh, RewardPopup
│ ├── nav/ BottomNav.jsx, Sidebar.jsx
│ ├── layout/ AppTopBar.jsx
│ ├── 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, GuideModal, GuestGuideBanner, AdCard, AdSlot, ...
│
├── styles/
│ ├── index.css # Точка входа CSS
│ ├── base.css # Переменные, сброс, keyframes
│ ├── layout.css, sidebar.css, card.css, modal.css, ui.css
│ ├── chat.css, desktop.css, guide.css
│ └── reviews.css, rules.css, admin.css, NakhodkaLanding.css
│
└── locales/
├── ru.json
└── en.json
```
---
## 6. Маршруты
| Путь | Компонент | Доступ |
|------|-----------|--------|
| `/` | `NakhodkaLanding` | публичный лендинг |
| `/feed` | `MainFeed` | лента (главная) |
| `/reviews` | `ReviewsPage` | отзывы о площадке |
| `/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. Ключевые компоненты
### `MainFeed.tsx`
Главная страница. Собирает топбар, поиск, фильтры, ленту, сайдбары, карту,
модалки (объявление, профиль, вход, правила, поддержка, просмотр фото).
Делегирует загрузку и мутации хукам `useFeedPosts`, `useCityFeed`, `useSearchPosts`,
`useMyPosts`, `useFeedActions`, `useModals`. Ошибки удаления/отметки «найдено»
показываются через `Toast`.
### `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`
Модалка создания/редактирования. Переключатель Потеря/Находка, заголовок,
описание, фото (сжатие на клиенте, на десктопе — и перетаскиванием, `useFileDropZone`),
категория, карта Яндекса с меткой и обратным геокодированием, адрес, телефон с маской
(подставляется из профиля) и галочка согласия на показ номера (`phoneVisible`: без неё
номер не отправляется и не хранится), вознаграждение (только у потерь), до трёх контрольных
вопросов (JSON-массивом в `verificationQuestions`) и блок «Как не попасться мошенникам», чекбокс правил.
Валидация — `validatePostForm`. С пропом `adminMode` шлёт `PUT /api/v1/admin/posts/{id}`
и не меняет согласие автора.
### `FeedContent.jsx` / `FeedTopBar.tsx` / `PullToRefresh.jsx`
Лента, топбар со спрятанной панелью на скролле, pull-to-refresh с корректным
cleanup класса активности.
### `MapView.jsx`
Полноэкранная карта. Ждёт готовности API Яндекса, показывает плашку ошибки,
если он не загрузился. Первая загрузка маркеров идёт по фактическим границам
карты, а не по событию `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`
Админ-панель: вкладки «Рекламные кампании» и «Все объявления».
Кампании, реклама, загрузка видео (presigned → S3 → confirm), фуллскрин-реклама.
`PostsTab` — список всех объявлений с поиском, фильтрами, пагинацией, правкой,
закрытием/возвратом в ленту и удалением.
---
## 8. Контексты
### `AuthContext`
```js
{
user, // object | null
token, // string | null — JWT
isAuthenticated, // !!token
isAdmin, // user.role === "ADMIN" — только скрытие UI, не защита
login(user, token, refreshToken), // пишет в localStorage + state
logout(), // POST /auth/logout (отзыв refresh-токена) + чистит localStorage + state
updateUser(userData), // обновляет пользователя; если в ответе есть token/refreshToken
// (смена своего логина) — сохраняет новую пару, в user их не кладёт
}
```
Хранится в `localStorage`: `user` (JSON), `token`, `refreshToken`.
Хук: `useAuthContext()`. Значение контекста мемоизировано; вход/выход в другой
вкладке подхватывается через событие `storage`.
### `ThemeContext`
Светлая/тёмная тема; выбор сохраняется.
### `UnreadContext`
Счётчики непрочитанных по чатам; сбрасываются при смене пользователя,
данные приходят из WS-подписки `/topic/user/{userId}/unread`.
---
## 9. Хуки
### Авторизация и API
| Хук | Назначение |
|-----|-----------|
| `apiClient.jsx` → `apiFetch` | `fetch` + `Authorization` + refresh: истекающий токен (по `exp`) обновляется заранее, на 401 — один refresh на все параллельные запросы и вкладки (Web Locks), refresh отклонён → `SessionExpiredError` и выход; сбой сети/429/5xx на refresh не разлогинивает |
| `apiErrors.js` | `ApiError`, `readApiError(res)` (формат `{status, error, message, details}`), `describeApiError(err, fallback)` — текст для UI: 429 «повторите через N мин» (по `Retry-After`, если он виден), 413, сбой сети, сообщение сервера для 4xx |
| `useProfile.js` | Загрузка профиля |
| `useUpdateProfile.js` | Обновление профиля с аватаром |
### Объявления
| Хук | Назначение |
|-----|-----------|
| `useFeedPosts.jsx` | Лента с пагинацией, request-id guard, дедупликация |
| `useCityFeed.jsx` | Лента по городу |
| `useSearchPosts.js` | Поиск с дебаунсом |
| `useMyPosts.jsx` | Мои объявления: `GET /api/v1/users/{id}/posts` (все страницы); с токеном, поэтому видны и неопубликованные (метки «На модерации»/«Отклонено») |
| `useFeedActions.jsx` | Удаление и отметка «найдено» + `error`/`clearError` |
| `usePostMutation.js` | Создание/обновление (обычное и `adminMode`) |
| `useDeletePost.js`, `usePostStatus.js` | Точечные мутации |
| `useImageUpload.js` | Выбор, сжатие, превью изображений; `clearImages` — сброс после отправки |
| `useFileDropZone.js` | Перетаскивание файлов (форма объявления, аватар); файл, брошенный мимо зоны, не открывается браузером |
| `useRevealPhone.js` | «Показать номер»: задача → решение (`utils/proofOfWork.js`) → номер; 429 и ошибки — текстом |
| `useModals.jsx` | Управление модалками |
| `useInfiniteScroll.jsx` | Бесконечная прокрутка с cleanup `IntersectionObserver` |
| `useCities.js`, `useCityOptions.js`, `useClickOutside.jsx`, `useIsDesktop.js`, `useHideOnScroll.js`, `useProfileData.js` | Вспомогательные |
### Реклама
| Хук | Назначение |
|-----|-----------|
| `useFullscreenAdTrigger.js` | Показ фуллскрин-рекламы |
| `useAdViewability.js` | Показ засчитывается, когда ≥ 50% баннера видно ≥ 1 с подряд (IAB/MRC); фоновая вкладка не считается |
| `api/adsApi.js` | `getNextAd` (с `X-Session-Id`), `trackAdImpression` / `trackAdClick` с `impressionToken`; показ без входа — `navigator.sendBeacon` (`text/plain`) |
| `useTranscodingStatusPolling.js` | Статус транскодинга видео: сброс между роликами, fallback `PROCESSING`, лимит попыток |
### Чат
| Хук | Назначение |
|-----|-----------|
| `useStompClient.js` | Общий STOMP-клиент: reconnect, истекающий токен обновляется в `beforeConnect`, после отказа CONNECT — принудительный refresh (не чаще раза в минуту), мёртвая сессия останавливает переподключения |
| `useChatSocket.js` | Подписка на чат, отправка сообщений, ошибки отправки из `/user/queue/errors` (флаг `REACT_APP_WS_ERROR_QUEUE`) |
| `useUnreadSocket.js` | Непрочитанные |
| `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` | Удаление чата |
### Карта и локация
| Хук | Назначение |
|-----|-----------|
| `useGeolocation.js` | Геолокация пользователя со статусами |
| `useYandexMap.js` | Инициализация карты, метка (drag), обратное геокодирование, ошибка загрузки API |
### Прочее
| Хук | Назначение |
|-----|-----------|
| `useReviews.jsx` | Отзывы: загрузка, отправка, средний рейтинг и распределение |
| `useLanguageToggle.js` | Переключение ru/en |
---
## 10. API-эндпоинты
Базовый URL — `REACT_APP_API_URL`. Защищённые эндпоинты вызываются через
`apiFetch`, который сам добавляет `Authorization: Bearer <JWT>` и обновляет
токен при 401.
### Аутентификация
| Метод | Endpoint | Тело | Ответ |
|-------|----------|------|-------|
| `POST` | `/api/v1/auth/login` | `{ login, password }` | `{ token, refreshToken, user }` |
| `POST` | `/api/v1/auth/register` | `{ name, login, password }` | `{ token, refreshToken, user }` |
| `POST` | `/api/v1/auth/refresh` | `{ refreshToken }` | `{ token, refreshToken }`; токен **одноразовый**, повтор → 401 |
| `POST` | `/api/v1/auth/logout` | `{ refreshToken }` | 204 |
Пароль при регистрации — от 8 символов и не длиннее 72 байт в UTF-8
(`utils/passwordPolicy.js`, так же проверяет бэкенд). Ошибки входа и
регистрации — `400 {message}`; лимиты запросов и блокировка аккаунта после
10 неудачных входов на 15 минут — `429`, без автоповтора.
### Объявления
| Метод | Endpoint | Назначение |
|-------|----------|-----------|
| `GET` | `/api/v1/posts?page=&size=&…` | Лента с пагинацией (`content` / `items` / массив) |
| `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/: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`),
потом бэкенд его удаляет.
### Профиль
| Метод | Endpoint | Назначение |
|-------|----------|-----------|
| `GET` | `/api/v1/users/:userId` | Профиль; у чужого `email` и `phone` = `null` |
| `PUT` | `/api/v1/users/:userId` | Обновить профиль (`FormData`); при смене своего логина в ответе новые `token`/`refreshToken` |
### Чаты
| Метод | Endpoint | Назначение |
|-------|----------|-----------|
| `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 | Тело |
|-------|----------|------|
| `GET` | `/api/v1/reviews` | — |
| `POST` | `/api/v1/reviews` | `{ rating, text }` |
### Файлы и реклама
| Метод | Endpoint | Назначение |
|-------|----------|-----------|
| `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` |
`targetUrl` открывается только если это абсолютный `http(s)` (`utils/safeUrl.js`),
через `<a target="_blank" rel="noopener noreferrer sponsored">`. `X-Session-Id` —
стабильный id устройства из `localStorage` (`utils/adSession.js`), формат
`[A-Za-z0-9._:-]{1,64}`.
**`ADS_REQUIRE_TRACKING_TOKEN=true`** на бэкенде можно включать, когда этот
фронт задеплоен: все показы и клики отправляются с токеном показа.
Значения категорий в запросах — **стабильные русские строки** (`Вещь`, `Питомец`,
`Другое`): они хранятся в БД, поэтому не переводятся вместе с интерфейсом.
Локализованы только подписи (`feedConstants.js` → `CATEGORIES`).
---
## 11. WebSocket
STOMP поверх SockJS: `${REACT_APP_API_URL}/ws` (токен передаётся при подключении).
| Назначение | Путь |
|-----------|------|
| Подписка на чат | `/topic/chat/{chatId}` — новые сообщения и обновлённые (видео обработалось); `ChatPage` заменяет сообщение с тем же `id` |
| Подписка на непрочитанные | `/topic/user/{userId}/unread` |
| Ошибки отправки (флаг `REACT_APP_WS_ERROR_QUEUE`) | `/user/queue/errors` |
| Отправка сообщения | `/app/chat.send` |
CONNECT — с заголовком `Authorization: Bearer <access>`; refresh-JWT как access
бэкенд не принимает.
Общий клиент — `useStompClient`: единый STOMP-клиент с reconnect, обработкой
закрытия соединения и ошибок активации; колбэки хранятся в ref, поэтому
переподписка не пересоздаёт подключение.
---
## 12. Админские эндпоинты
Админ-панель живёт на `/admin/ads` (только для `isAdmin`, только десктоп) и
переключается вкладками:
- `/admin/ads` — рекламные кампании;
- `/admin/ads?tab=posts` — «Все объявления».
### Общие требования
- Префикс `/api/v1/admin`, все запросы с `Authorization: Bearer <JWT>`.
- **Роль `ADMIN` обязана проверяться на сервере по каждому эндпоинту.**
Клиентский `isAdmin` — только скрытие UI; подделка `localStorage` не должна
давать доступ к чужим объявлениям и переписке.
- Тело ошибок — JSON `{"message": "..."}`; фронт показывает этот текст.
- Пагинация как у `GET /api/v1/posts`: `{ "content": [...], "last": bool, "totalElements": N }`.
Фронт принимает и `content`, и `items`, и голый массив.
### Реклама (работает)
`/api/v1/admin/campaigns`, `/api/v1/admin/ads`, `/api/v1/admin/fullscreen-ads`.
- **Статистика кампании** — кнопка «Статистика» в карточке кампании
(`components/admin/CampaignStatsPanel.jsx`): `GET /api/v1/admin/campaigns/{id}/stats?from=&to=`,
показы, клики и CTR по кампании и каждому объявлению, по умолчанию за
последние 30 дней (максимум 366). Старый бэкенд отвечает 404 — панель так и пишет.
- Дневной лимит показов — на кампанию за календарные сутки (`ads.timezone`);
кампании сами переходят в `FINISHED` по `endDate`.
- `targetUrl` — только абсолютный `http(s)`, иначе 400; форма проверяет так же.
- Видео: если загрузка в MinIO или `confirm-upload` упали, повторная отправка
формы продолжает с того же объявления, а не создаёт новое.
### Объявления
#### `GET /api/v1/admin/posts`
Параметры (все опциональны): `page` (с 0), `size` (по умолчанию 20, максимум 100),
`search`, `type` (`LOSS`/`FOUND`), `status`.
Видны **все** статусы, включая `MODERATION` и `REJECTED`. Сортировка по умолчанию —
новые сверху (`createdAt DESC`). `search` ищет без учёта регистра по названию,
описанию, городу, району и данным владельца (login, имя, фамилия).
Элемент `content` — то же, что у публичного объявления, плюс данные автора
(`ownerId`, `ownerLogin`, `ownerName`, `ownerFirstName`, `ownerLastName`).
Фронт читает автора с запасом (`ownerLogin` / `authorLogin` / `userLogin` и т. п.).
#### `PUT /api/v1/admin/posts/{postId}`
`multipart/form-data`, как у пользовательского `PUT /api/v1/posts/{id}`:
`type`, `title`, `description`, `category`, `phone`, `reward`, `rewardText`,
`images`, `existingImages`, `latitude`, `longitude`, `address`.
Ответ `200` — обновлённое объявление.
Отличия от пользовательской правки:
- **Статус сохраняется** — админ чинит объявление, не убирая его из ленты
(`MODERATION` отправил бы на повторную AI-модерацию, `REJECTED` скрыл бы навсегда).
Смена статуса — отдельным `PATCH`.
- Падение геокодинга не блокирует правку: город берётся из `address`.
- Изображения, которых нет в `existingImages`, удаляются.
#### `DELETE /api/v1/admin/posts/{postId}`
Ответ `204 No Content`. Вместе с объявлением чистятся изображения в хранилище,
записи из `favorites` и обнуляется `post_id` в чатах.
#### `PATCH /api/v1/admin/posts/{postId}/status`
Тело `{ "status": "CLOSED" }` — закрыть («найдено»), `{ "status": "ACTIVE" }` —
вернуть в ленту. Принимаются все `PostStatus`: `ACTIVE`, `CLOSED`, `MODERATION`,
`REJECTED` (фронт отдаёт первые два). Переход в `CLOSED` увеличивает `posts_found`.
Неизвестный статус — `400`.
### Чаты (вкладка не сделана)
Требуемые эндпоинты:
| Метод | Endpoint | Назначение |
|-------|----------|-----------|
| `GET` | `/api/v1/admin/chats?page&size&search&postId` | Список чатов с превью |
| `GET` | `/api/v1/admin/chats/{chatId}/messages` | Сообщения чата |
| `POST` | `/api/v1/admin/chats/{chatId}/messages` | Написать в чат (`{ "content": "…" }`) |
| `DELETE` | `/api/v1/admin/chats/{chatId}` | Удалить чат с перепиской |
**Важно:** `senderId` должен браться **из JWT, а не из тела запроса**, иначе админ
мог бы слать сообщения от имени пользователей. Авторизация — только `ADMIN`;
это осознанное расширение прав по сравнению с пользовательским чатом
(например, чтобы предупредить о мошенничестве).
### Что сделано на клиенте
- `src/api/adminContentApi.js` — `getAdminPosts`, `deleteAdminPost`,
`updateAdminPostStatus`; пагинация принимает `content` / `items` / массив;
`type` нормализуется в `loss`/`found`.
- `CreateUpdatePost` с пропом `adminMode` → `usePostMutation` шлёт
`PUT /api/v1/admin/posts/{id}` (форма и валидация общие с пользовательской).
- `src/components/admin/PostsTab.jsx` — список, поиск с дебаунсом, фильтры,
«Показать ещё», карточки с действиями.
### Что осталось на клиенте
- Вкладка «Все чаты» (`ChatsTab.jsx` не создана) — ждёт эндпоинтов чатов.
- Проверка роли и скрытие UI: `AuthContext.isAdmin`, `AdminRoute` в `App.js`,
`isAdmin` в сайдбаре. Это удобство, не защита.
- Админка не постит сообщения через STOMP: используется REST, чтобы реплика
не зависела от того, разрешена ли админу подписка `/topic/chat/{id}`.
### Статус бэкенда
Репозиторий бэкенда: `D:\reFound\ReFound`.
| Файл | Назначение |
| --- | --- |
| `controller/admin/PostAdminController.java` | Эндпоинты объявлений, у каждого `@PreAuthorize("hasRole('ADMIN')")` |
| `service/admin/AdminPostService.java` | Логика: список, правка, удаление, статус |
| `dto/admin/AdminPostResponse.java` | Объявление + данные владельца |
| `dto/admin/AdminPostStatusUpdateRequest.java` | `{ "status": "..." }` |
| `util/PostSpecification.java` | `adminSearch` — поиск по полям объявления и владельца |
| `repository/ImageRepository.java` | `findByPostIdIn` — картинки страницы одним запросом вместо N+1 |
| `repository/ChatRepository.java` | `clearPostReference` — обнуление `post_id` при удалении |
| `test/.../AdminPostServiceTest.java` | 13 тестов: поиск, фильтры, статус, статистика, картинки, кэш |
Защита дублируется: `SecurityConfig` требует `ADMIN` на `/api/v1/admin/**`,
и методы контроллера дополнительно закрыты `@PreAuthorize`.
---
## 13. Стили и темы
Подключение через `src/styles/index.css`:
```
index.css → base.css → layout.css → sidebar.css → card.css → modal.css → ui.css
```
Дополнительно подключаются в компонентах: `chat.css` и `desktop.css` (`App.js`),
`reviews.css`, `rules.css`, `admin.css`, `NakhodkaLanding.css`.
CSS-переменные в `base.css`:
| Переменная | Значение | Описание |
|-----------|----------|----------|
| `--teal` | `#2de0c8` | Основной акцент |
| `--teal2` | `#1fc9b0` | Тёмный оттенок |
| `--border` | `rgba(255,255,255,0.09)` | Границы |
| `--muted` / `--muted2` | `rgba(255,255,255,.38)` / `.15` | Второстепенный текст |
| `--font` | `Nunito`, sans-serif | Шрифт |
| `--err` | `#ff6b6b` | Ошибка |
Тёмная тема — градиентные фоны, «стекло» (`backdrop-filter`), акцент `#2de0c8`;
светлая переключается через `ThemeContext`.
Адаптивность:
| Брейкпоинт | Что меняется |
|------------|-------------|
| `≥ 900px` | Десктопная раскладка (`desktop.css`, `useIsDesktop`): левая навигация, двухпанельные чаты, карта со списком |
| `≤ 900px` | Правый сайдбар скрывается, навигация внизу |
| `≤ 768px` | Компактные отступы и кнопки |
| `≤ 600px` | Модалки на всю ширину |
---
## 14. Основные сценарии
**Аутентификация.** Гость нажимает «Разместить», «Мои объявления» или аватар →
открывается `AuthModal` → `POST /api/v1/auth/login` → `AuthContext.login()`
сохраняет `user`, `token`, `refreshToken` в `localStorage`. Просрочка access-токена
обрабатывается прозрачно: `apiFetch` при 401 обновляет токен и повторяет запрос;
при неудаче чистит сессию.
**Создание объявления.** Авторизованный пользователь → `CreateUpdatePost` →
заполняет форму → клиентское сжатие фото → `POST /api/v1/posts` (`FormData`) →
лента обновляется.
**Поиск и чат.** «Написать» → `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 метки и клик переводят
координаты в адрес через Яндекс.Геокодер; запрос на геокодинг защищён
request-id от гонок.
**Профиль.** Аватар в топбаре → `ProfileModal` → `PUT /api/v1/users/:id` →
данные обновляются в `AuthContext` и `localStorage`; «Выйти» — очистка сессии.
---
## 15. Известные проблемы и предупреждения
- **`fs.F_OK is deprecated`** при сборке — предупреждение Node 24 из внутренностей
`react-scripts@5`. Не влияет на результат; уходит при переходе на CRA 6 / Vite.
- **`npm audit`** показывает уязвимости в транзитивных зависимостях CRA
(webpack-dev-server и др.). Применять `npm audit fix --force` нельзя: это
ломающие обновления в пределах `react-scripts@5`.
- **Ключи Яндекса** попадали в историю git — их нужно перевыпустить.
- **Клиентская проверка роли** (`isAdmin`, `AdminRoute`) — только скрытие UI.
Реальная авторизация обязана быть на сервере по каждому эндпоинту.
- **Бэкенд до ветки backend-review** отвечал `500` на битый JSON и неверные
параметры; новый отдаёт корректные 400/401/403/404/413/422. Фронт разбирает
оба варианта (`api/apiErrors.js`).
- **Фронт и бэкенд деплоятся парой, бэкенд — первым.** Фронт из `master` рассчитан на
бэкенд из `master`: одно объявление по `GET /api/v1/posts/{id}`, показ номера по
proof-of-work, вложения в чатах. Со старым бэкендом не работают «Мои объявления»,
карточка с карты, номер телефона и отправка фото/видео.
- **`Retry-After`** виден фронту, только если бэкенд отдаёт его в
`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`.
- **Токены в `localStorage`** доступны любому скрипту на странице (XSS → кража
сессии). Перенос refresh-токена в `HttpOnly`-cookie требует изменений на
бэкенде (CORS с credentials, CSRF) — отдельная задача.
- **Деплой:** `.gitea/workflows/deploy.yml` срабатывает на push в `main`, а
основная ветка репозитория — `master`.

38
nginx.conf Normal file
View File

@@ -0,0 +1,38 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
# Сжатие JS/CSS/JSON/SVG: бандл CRA без него весит в 3–4 раза больше
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css application/javascript application/json image/svg+xml text/plain;
# Базовые заголовки безопасности. CSP не задаём: Яндекс.Карты, MinIO и
# домен API нужно сначала перечислить (см. README, «Безопасность»).
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "DENY" always;
# Хешированные файлы CRA — навсегда в кэш
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
# add_header в location отменяет заголовки уровня server — повторяем
add_header X-Content-Type-Options "nosniff" always;
}
# index.html не кэшируем: иначе после деплоя браузер держит старую
# страницу со ссылками на удалённые бандлы (белый экран)
location = /index.html {
add_header Cache-Control "no-cache";
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "DENY" always;
}
location / {
try_files $uri /index.html;
}
}

1464
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,25 +3,14 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@hookform/resolvers": "^5.2.2",
"@pbe/react-yandex-maps": "^1.2.5",
"@stomp/stompjs": "^7.3.0",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/react-query": "^5.100.5",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^13.5.0",
"autoprefixer": "^10.5.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"emoji-mart": "^5.6.0",
"framer-motion": "^12.38.0",
"i18next": "^22.5.1",
"lucide-react": "^1.11.0",
"postcss": "^8.5.12",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.74.0",
@@ -29,16 +18,16 @@
"react-router-dom": "^7.14.2",
"react-scripts": "5.0.1",
"sockjs-client": "^1.6.1",
"tailwind-merge": "^3.5.0",
"tailwindcss": "^4.2.4",
"web-vitals": "^2.1.4",
"zod": "^4.3.6",
"zustand": "^5.0.12"
"zod": "^4.3.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"test:ci": "react-scripts test --watchAll=false --testMatch \"**/src/**/*.test.{js,jsx,ts,tsx}\"",
"lint": "eslint src --ext .js,.jsx,.ts,.tsx --max-warnings=0",
"typecheck": "tsc --noEmit",
"eject": "react-scripts eject"
},
"eslintConfig": {
@@ -61,8 +50,11 @@
},
"devDependencies": {
"@types/node": "^25.6.0",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"typescript": "^4.9.5"
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"typescript": "^5.9.3"
},
"overrides": {
"caniuse-lite": "^1.0.30001814"
}
}

BIN
public/apple-touch-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

16
public/favicon.svg Normal file
View File

@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#45484E"/>
<stop offset="1" stop-color="#26282C"/>
</linearGradient>
<linearGradient id="heart" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#FF8E6B"/>
<stop offset="1" stop-color="#F1503A"/>
</linearGradient>
</defs>
<rect width="64" height="64" rx="15" fill="url(#bg)"/>
<circle cx="27.5" cy="27.5" r="14.5" fill="#FFFFFF" fill-opacity="0.18" stroke="#FFFFFF" stroke-width="6"/>
<path d="M38.5 38.5 L50 50" stroke="#FFFFFF" stroke-width="7.5" stroke-linecap="round"/>
<path d="M27.5 35 C21 30.6 20.3 26.6 22.5 24.3 C24.4 22.4 26.6 23 27.5 24.9 C28.4 23 30.6 22.4 32.5 24.3 C34.7 26.6 34 30.6 27.5 35 Z" fill="url(#heart)"/>
</svg>

After

Width:  |  Height:  |  Size: 848 B

View File

@@ -2,15 +2,33 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<!-- SVG — для современных браузеров (чёткая на любом DPI), ICO — запасной вариант -->
<link rel="icon" href="%PUBLIC_URL%/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" sizes="48x48" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<script defer src="https://api-maps.yandex.ru/2.1/?apikey=%REACT_APP_YANDEX_MAPS_KEY%&lang=ru_RU" type="text/javascript"></script>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/apple-touch-icon.png" />
<!--
Шрифты 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&amp;family=Literata:opsz,wght@7..72,400;7..72,500;7..72,600;7..72,700&amp;family=Inter:wght@400;500;600;700&amp;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&amp;family=Literata:opsz,wght@7..72,400;7..72,500;7..72,600;7..72,700&amp;family=Inter:wght@400;500;600;700&amp;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/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -1,10 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"short_name": "Находка",
"name": "Находка",
"icons": [
{
"src": "favicon.svg",
"type": "image/svg+xml",
"sizes": "any"
},
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"sizes": "48x48 32x32 16x16",
"type": "image/x-icon"
},
{

View File

@@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>react_front</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.3 KiB

View File

@@ -1,184 +0,0 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

View File

@@ -1,122 +0,0 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
type="button"
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
<div className="ticks"></div>
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
}
export default App

View File

@@ -1,111 +0,0 @@
:root {
--text: #6b6375;
--text-h: #08060d;
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
#root {
width: 1126px;
max-width: 100%;
margin: 0 auto;
text-align: center;
border-inline: 1px solid var(--border);
min-height: 100svh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
body {
margin: 0;
}
h1,
h2 {
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
}
h1 {
font-size: 56px;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
}

View File

@@ -1,10 +0,0 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -1,38 +0,0 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@@ -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,8 +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/: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>

View File

@@ -16,6 +16,14 @@ export class AdminApiError extends Error {
}
}
/** Ошибка с текстом сервера в serverMessage (пусто, если сервер его не прислал). */
async function adminError(res, fallback) {
const message = await readErrorMessage(res, null);
const err = new AdminApiError(res.status, message || fallback);
err.serverMessage = message || "";
return err;
}
async function readErrorMessage(res, fallback) {
try {
const body = await res.json();
@@ -34,7 +42,7 @@ async function readErrorMessage(res, fallback) {
*/
export async function getCampaigns() {
const res = await apiFetch(`${ADMIN_BASE}/campaigns`);
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load campaigns"));
if (!res.ok) throw await adminError(res, "Failed to load campaigns");
return res.json();
}
@@ -44,7 +52,7 @@ export async function createCampaign({ name, startDate, endDate, dailyImpression
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create campaign"));
if (!res.ok) throw await adminError(res, "Failed to create campaign");
return res.json();
}
@@ -57,7 +65,7 @@ export async function updateCampaignStatus(campaignId, status) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update status"));
if (!res.ok) throw await adminError(res, "Failed to update status");
return res.json();
}
@@ -72,7 +80,24 @@ export async function updateCampaign(campaignId, { name, startDate, endDate, dai
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, startDate, endDate, dailyImpressionCap }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update campaign"));
if (!res.ok) throw await adminError(res, "Failed to update campaign");
return res.json();
}
/**
* GET /api/v1/admin/campaigns/{id}/stats?from=YYYY-MM-DD&to=YYYY-MM-DD —
* показы, клики и CTR (%) кампании и каждого её объявления за дни from..to
* включительно (по умолчанию бэкенд берёт последние 30 дней, максимум 366).
* Ответ: {campaignId, from, to, impressions, clicks, ctr, advertisings: [...]}.
* Старый бэкенд маршрута не знает — 404.
*/
export async function getCampaignStats(campaignId, { from, to } = {}) {
const params = new URLSearchParams();
if (from) params.set("from", from);
if (to) params.set("to", to);
const query = params.toString();
const res = await apiFetch(`${ADMIN_BASE}/campaigns/${encodeURIComponent(campaignId)}/stats${query ? `?${query}` : ""}`);
if (!res.ok) throw await adminError(res, "Failed to load stats");
return res.json();
}
@@ -84,7 +109,7 @@ export async function updateCampaign(campaignId, { name, startDate, endDate, dai
*/
export async function getAdvertisingsByCampaign(campaignId) {
const res = await apiFetch(`${ADMIN_BASE}/ads?campaignId=${encodeURIComponent(campaignId)}`);
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load advertisings"));
if (!res.ok) throw await adminError(res, "Failed to load advertisings");
return res.json();
}
@@ -98,7 +123,7 @@ export async function createAdvertising({ campaignId, type, mediaKey, targetUrl,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ campaignId, type, mediaKey, targetUrl, weight }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create advertising"));
if (!res.ok) throw await adminError(res, "Failed to create advertising");
return res.json();
}
@@ -112,7 +137,7 @@ export async function updateAdvertising(advertisingId, { targetUrl, weight }) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targetUrl, weight }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to update advertising"));
if (!res.ok) throw await adminError(res, "Failed to update advertising");
return res.json();
}
@@ -128,7 +153,7 @@ export async function uploadAdImage(file) {
method: "POST",
body: formData,
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to upload image"));
if (!res.ok) throw await adminError(res, "Failed to upload image");
return res.json(); // { mediaKey }
}
@@ -138,7 +163,7 @@ export async function presignVideoUpload(advertisingId, contentType) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Presign failed"));
if (!res.ok) throw await adminError(res, "Presign failed");
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
}
@@ -151,13 +176,13 @@ export async function confirmVideoUpload(advertisingId, sourceKey) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sourceKey }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Confirm upload failed"));
if (!res.ok) throw await adminError(res, "Confirm upload failed");
return res;
}
export async function getAdvertisingStatus(advertisingId) {
const res = await apiFetch(`${ADMIN_BASE}/ads/${advertisingId}/status`);
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Status check failed"));
if (!res.ok) throw await adminError(res, "Status check failed");
return res.json(); // { advertisingId, transcodingStatus }
}
@@ -168,7 +193,7 @@ export async function getAdvertisingStatus(advertisingId) {
*/
export async function getFullscreenAds() {
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads`);
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to load fullscreen ads"));
if (!res.ok) throw await adminError(res, "Failed to load fullscreen ads");
return res.json();
}
@@ -181,7 +206,7 @@ export async function createFullscreenAd({ targetUrl }) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targetUrl: targetUrl || null }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Failed to create fullscreen ad"));
if (!res.ok) throw await adminError(res, "Failed to create fullscreen ad");
return res.json();
}
@@ -191,7 +216,7 @@ export async function presignFullscreenVideoUpload(fullscreenAdId, contentType)
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Presign failed"));
if (!res.ok) throw await adminError(res, "Presign failed");
return res.json(); // { uploadUrl, sourceKey, expiryMinutes }
}
@@ -204,7 +229,7 @@ export async function confirmFullscreenVideoUpload(fullscreenAdId, sourceKey) {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sourceKey }),
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Confirm upload failed"));
if (!res.ok) throw await adminError(res, "Confirm upload failed");
return res;
}
@@ -216,7 +241,7 @@ export async function activateFullscreenAd(fullscreenAdId) {
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/activate`, {
method: "PATCH",
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Activate failed"));
if (!res.ok) throw await adminError(res, "Activate failed");
return res.json();
}
@@ -224,6 +249,6 @@ export async function deactivateFullscreenAd(fullscreenAdId) {
const res = await apiFetch(`${ADMIN_BASE}/fullscreen-ads/${fullscreenAdId}/deactivate`, {
method: "PATCH",
});
if (!res.ok) throw new AdminApiError(res.status, await readErrorMessage(res, "Deactivate failed"));
if (!res.ok) throw await adminError(res, "Deactivate failed");
return res.json();
}

126
src/api/adminContentApi.js Normal file
View File

@@ -0,0 +1,126 @@
// src/api/adminContentApi.js
//
// Админские эндпоинты для контента площадки (объявления). Здесь только то, что
// нельзя завернуть в общий хук: правка объявления идёт через usePostMutation
// с опцией adminMode — там же живёт сборка FormData и разбор ошибок модерации.
import { API_URL } from "../config/authConstants";
import { apiFetch } from "./apiClient";
const ADMIN_BASE = `${API_URL}/api/v1/admin`;
/**
* Ошибка админ-эндпоинтов контента (объявления). Несёт HTTP-статус,
* чтобы UI мог отличить 403 (нет роли ADMIN) от 404 и сетевых сбоев.
*/
export class AdminContentError extends Error {
constructor(status, message) {
super(message || `Admin content API error ${status}`);
this.name = "AdminContentError";
this.status = status;
}
}
async function readErrorMessage(res, fallback) {
try {
const body = await res.json();
if (body && typeof body.message === "string") return body.message;
if (body && typeof body.error === "string") return body.error;
} catch {
// тело не JSON (например, 204/пустой ответ) — используем fallback
}
return fallback;
}
/**
* Приводит объявление к тому виду, в котором его ждёт лента:
* type в нижний регистр ("loss"/"found"). Остальные хуки (useFeedPosts,
* useMyPosts) нормализуют так же — иначе карточка PostOnFeed отрисовалась бы
* с типом "находка" у потерянного объявления.
*/
function normalizePost(post) {
if (!post) return post;
return {
...post,
type: post.type ? String(post.type).toLowerCase() : "loss",
};
}
/** Достаёт элементы страницы: бэкенд отдаёт {content|last}, {items}, либо массив. */
function extractPage(body, size) {
if (Array.isArray(body)) {
return { items: body.map(normalizePost), last: body.length < size, total: body.length };
}
const rawItems = body?.content ?? body?.items ?? [];
const items = Array.isArray(rawItems) ? rawItems.map(normalizePost) : [];
const hasTotal = typeof body?.totalElements === "number";
const last = typeof body?.last === "boolean"
? body.last
// Без метаданных пагинации решаем по размеру страницы: недобор = это конец.
: hasTotal
? body.totalElements <= (body?.number ?? 0) + items.length
: items.length < size;
return { items, last, total: hasTotal ? body.totalElements : undefined };
}
/**
* GET /api/v1/admin/posts?page&size&search&type&status
*
* Постранично отдаёт ВСЕ объявления площадки вместе с данными автора.
* Возвращает { items, last, total } — items уже нормализованы.
*/
export async function getAdminPosts({ page = 0, size = 20, search = "", type = "", status = "" } = {}) {
const params = new URLSearchParams({ page, size });
if (search) params.set("search", search);
if (type) params.set("type", type);
if (status) params.set("status", status);
const res = await apiFetch(`${ADMIN_BASE}/posts?${params.toString()}`);
if (!res.ok) throw new AdminContentError(res.status, await readErrorMessage(res, "Failed to load posts"));
return extractPage(await res.json(), size);
}
/**
* GET /api/v1/admin/posts/rejected?page&size&search&type&status
*
* Постранично отдаёт объявления, не прошедшие модерацию (REJECTED),
* вместе с данными автора.
* Возвращает { items, last, total } — items уже нормализованы.
*/
export async function getAdminRejectedPosts({ page = 0, size = 20, search = "", type = "", status = "" } = {}) {
const params = new URLSearchParams({ page, size });
if (search) params.set("search", search);
if (type) params.set("type", type);
if (status) params.set("status", status);
const res = await apiFetch(`${ADMIN_BASE}/posts/rejected?${params.toString()}`);
if (!res.ok) throw new AdminContentError(res.status, await readErrorMessage(res, "Failed to load rejected posts"));
return extractPage(await res.json(), size);
}
/** DELETE /api/v1/admin/posts/{postId} — 204 и 200 одинаково допустимы. */
export async function deleteAdminPost(postId) {
const res = await apiFetch(`${ADMIN_BASE}/posts/${encodeURIComponent(postId)}`, {
method: "DELETE",
});
if (!res.ok) throw new AdminContentError(res.status, await readErrorMessage(res, "Failed to delete post"));
return true;
}
/**
* PATCH /api/v1/admin/posts/{postId}/status — "найдено" (CLOSED)
* либо возврат объявления в ленту (ACTIVE).
*/
export async function updateAdminPostStatus(postId, status) {
const res = await apiFetch(`${ADMIN_BASE}/posts/${encodeURIComponent(postId)}/status`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
});
if (!res.ok) throw new AdminContentError(res.status, await readErrorMessage(res, "Failed to update status"));
try {
return normalizePost(await res.json());
} catch {
// Бэкенд может ответить без тела — тогда мержим только статус.
return { id: postId, status };
}
}

View File

@@ -1,5 +1,6 @@
import { API_URL } from "../config/authConstants";
import { apiFetch } from "./apiClient";
import { apiFetch, getAccessToken } from "./apiClient";
import { getAdSessionId } from "../utils/adSession";
/**
* Приводит mediaUrl рекламы к URL, доступному с устройства пользователя.
@@ -33,6 +34,84 @@ export function normalizeMediaUrl(mediaUrl) {
return url;
}
function authHeader() {
const token = getAccessToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
/**
* GET /api/ads/next — выбрать объявление для показа.
*
* X-Session-Id — стабильный id устройства: по нему (или по пользователю,
* если запрос авторизован) бэкенд считает дневной лимит и паузу между
* показами. Просроченный access-токен бэкенд просто игнорирует, поэтому
* refresh здесь не нужен — обычный fetch без apiFetch.
*
* @returns {Promise<{advertisingId, type, mediaUrl, targetUrl, impressionToken}|null>}
* null — показывать нечего (204: нет кандидатов, лимит, пауза, 429).
*/
export async function getNextAd(signal) {
const res = await fetch(`${API_URL}/api/ads/next`, {
headers: { "X-Session-Id": getAdSessionId(), ...authHeader() },
signal,
});
if (res.status === 204 || res.status === 429) return null;
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
if (!data?.advertisingId) return null;
return { ...data, mediaUrl: normalizeMediaUrl(data.mediaUrl) };
}
/** Тело /impression и /click: токен показа подтверждает, что реклама выдавалась. */
function trackingPayload(ad) {
return JSON.stringify({
advertisingId: ad.advertisingId,
sessionId: getAdSessionId(),
token: ad.impressionToken || null,
});
}
/**
* POST /api/ads/impression — реклама реально показана (см. useAdViewability).
*
* Без входа — navigator.sendBeacon (text/plain, бэкенд разбирает тело сам):
* доходит даже при закрытии вкладки. Залогиненным — fetch с keepalive и
* Authorization: показ без токена показа (старые объявления) учитывается по
* пользователю из заголовка, а sendBeacon заголовков не умеет.
*/
export function trackAdImpression(ad) {
if (!ad?.advertisingId) return;
const body = trackingPayload(ad);
const url = `${API_URL}/api/ads/impression`;
const auth = authHeader();
if (!auth.Authorization && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
try {
if (navigator.sendBeacon(url, new Blob([body], { type: "text/plain;charset=UTF-8" }))) return;
} catch {
// упадём на fetch ниже
}
}
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", ...auth },
body,
keepalive: true,
}).catch(() => {});
}
/** POST /api/ads/click — с тем же токеном показа. Ошибки трекинга не мешают переходу. */
export function trackAdClick(ad) {
if (!ad?.advertisingId) return;
fetch(`${API_URL}/api/ads/click`, {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeader() },
body: trackingPayload(ad),
keepalive: true,
}).catch(() => {});
}
/**
* GET /api/fullscreen-ad — активный полноэкранный ролик.
* 200 → { mediaUrl, targetUrl }; 204 → реклама не настроена.
@@ -63,30 +142,3 @@ export function putWithProgress(url, file, onProgress) {
xhr.send(file);
});
}
export async function uploadAdVideo(advertisingId, file, onProgress) {
const presignRes = await apiFetch(
`${API_URL}/api/v1/admin/ads/${advertisingId}/video/presign-upload`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType: file.type }),
}
);
if (!presignRes.ok) throw new Error(`Presign failed (${presignRes.status})`);
const { uploadUrl, sourceKey } = await presignRes.json();
await putWithProgress(uploadUrl, file, onProgress);
const confirmRes = await apiFetch(
`${API_URL}/api/v1/admin/ads/${advertisingId}/video/confirm-upload`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sourceKey }),
}
);
if (!confirmRes.ok) throw new Error(`Confirm failed (${confirmRes.status})`);
return { sourceKey };
}

View File

@@ -1,23 +1,86 @@
// src/api/apiClient.jsx
import { API_URL } from "../config/authConstants";
import { readApiError } from "./apiErrors";
const TOKEN_KEY = "token";
const REFRESH_TOKEN_KEY = "refreshToken";
const USER_KEY = "user";
// Имя Web Lock'а: refresh выполняет одна вкладка, остальные ждут её результата
const REFRESH_LOCK = "refound-token-refresh";
// Access-токен, которому осталось жить меньше этого, обновляем заранее
const EXPIRY_SKEW_MS = 30 * 1000;
// localStorage может бросать (приватный режим Safari, запрет хранилища) —
// без защиты падал бы любой запрос, а не только сохранение сессии.
function readStorage(key) {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function getAccessToken() {
return localStorage.getItem("token");
return readStorage(TOKEN_KEY);
}
function getRefreshToken() {
return localStorage.getItem("refreshToken");
return readStorage(REFRESH_TOKEN_KEY);
}
function saveTokens(token, refreshToken) {
localStorage.setItem("token", token);
localStorage.setItem("refreshToken", refreshToken);
try {
if (token) localStorage.setItem(TOKEN_KEY, token);
if (refreshToken) localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
} catch {
// хранилище недоступно — сессия проживёт до перезагрузки страницы
}
}
function clearTokens() {
localStorage.removeItem("token");
localStorage.removeItem("refreshToken");
localStorage.removeItem("user");
try {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
localStorage.removeItem(USER_KEY);
} catch {
// нечего чистить
}
}
/**
* Срок действия JWT (мс) из claim "exp" или null, если токен не JWT/без exp.
* Подпись не проверяем — это только подсказка, когда обновить токен заранее.
* Refresh-токен имеет вид "{uuid}.{jwt}" — берём три последних сегмента.
*/
export function getTokenExpiry(token) {
if (!token || typeof token !== "string") return null;
const parts = token.split(".");
if (parts.length < 3) return null;
try {
const base64 = parts[parts.length - 2].replace(/-/g, "+").replace(/_/g, "/");
const padded = base64 + "===".slice((base64.length + 3) % 4);
const payload = JSON.parse(atob(padded));
return typeof payload.exp === "number" ? payload.exp * 1000 : null;
} catch {
return null;
}
}
export function isTokenExpiring(token, now = Date.now()) {
const expiry = getTokenExpiry(token);
return expiry !== null && expiry - now < EXPIRY_SKEW_MS;
}
/**
* Refresh отклонён сервером (токен использован, отозван или истёк) —
* сессию не восстановить, нужен повторный вход. Сетевые сбои, 429 и 5xx
* сюда не относятся: из-за них разлогинивать пользователя нельзя.
*/
export class SessionExpiredError extends Error {
constructor() {
super("Session expired");
this.name = "SessionExpiredError";
}
}
let refreshPromise = null;
@@ -27,39 +90,95 @@ export function setOnSessionExpired(cb) {
onSessionExpired = cb;
}
export async function refreshAccessToken() {
/** Сессию не восстановить: чистим токены и сообщаем AuthContext. */
export function expireSession() {
clearTokens();
if (onSessionExpired) onSessionExpired();
}
/** Один POST /auth/refresh. Refresh-токен одноразовый: повтор того же → 401. */
async function requestNewTokens(usedRefreshToken) {
const res = await fetch(`${API_URL}/api/v1/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken: usedRefreshToken }),
});
if (res.status === 400 || res.status === 401 || res.status === 403) {
// Другая вкладка могла успеть обменять этот же токен раньше нас —
// тогда в хранилище уже лежит новая пара, и сессия жива.
if (getRefreshToken() !== usedRefreshToken && getAccessToken()) {
return getAccessToken();
}
throw new SessionExpiredError();
}
if (!res.ok) throw await readApiError(res);
const data = await res.json();
saveTokens(data.token, data.refreshToken);
return data.token;
}
/**
* Обновляет access-токен. Single-flight: параллельные вызовы в этой вкладке
* ждут один и тот же запрос, а между вкладками запрос сериализуется через
* Web Locks — иначе две вкладки отправили бы один и тот же одноразовый
* refresh-токен, и вторая получила бы 401 и разлогинила пользователя.
*
* @param {string} [staleAccessToken] — токен, с которым запрос получил 401.
* Если в хранилище уже другой (обновила другая вкладка/запрос), повторный
* refresh не нужен.
* @throws {SessionExpiredError} refresh отклонён — нужен вход
*/
export function refreshAccessToken(staleAccessToken) {
if (refreshPromise) return refreshPromise;
refreshPromise = (async () => {
const run = async () => {
const current = getAccessToken();
if (staleAccessToken && current && current !== staleAccessToken && !isTokenExpiring(current)) {
return current;
}
const refreshToken = getRefreshToken();
if (!refreshToken) throw new Error("No refresh token");
if (!refreshToken) throw new SessionExpiredError();
const refreshExpiry = getTokenExpiry(refreshToken);
if (refreshExpiry !== null && refreshExpiry <= Date.now()) throw new SessionExpiredError();
return requestNewTokens(refreshToken);
};
const res = await fetch(`${API_URL}/api/v1/auth/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
});
if (!res.ok) throw new Error("Refresh failed");
const data = await res.json();
saveTokens(data.token, data.refreshToken);
return data.token;
})();
try {
return await refreshPromise;
} finally {
refreshPromise = null;
}
const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
refreshPromise = (locks?.request ? locks.request(REFRESH_LOCK, run) : run())
.finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
/**
* Обёртка над fetch с авто-подстановкой Authorization и авто-обновлением
* access-токена при 401. Использовать вместо голого fetch для защищённых эндпоинтов.
* access-токена. Использовать вместо голого fetch для защищённых эндпоинтов.
*
* - истекающий токен обновляется заранее: публичные эндпоинты с просроченным
* токеном не отвечают 401, а просто считают запрос анонимным (и, например,
* не отдают владельцу его неопубликованные объявления);
* - на 401 — один refresh (общий для всех параллельных запросов) и повтор;
* - refresh отклонён — сессия очищается, бросается SessionExpiredError;
* - refresh не удался по сети/429/5xx — сессия сохраняется, возвращается
* исходный ответ 401.
*/
export async function apiFetch(url, options = {}) {
const token = getAccessToken();
let token = getAccessToken();
if (token && isTokenExpiring(token) && getRefreshToken()) {
try {
token = await refreshAccessToken(token);
} catch (e) {
if (e instanceof SessionExpiredError) {
expireSession();
token = null;
}
// временный сбой — пробуем со старым токеном, сервер решит сам
}
}
const doFetch = (accessToken) =>
fetch(url, {
@@ -72,15 +191,18 @@ export async function apiFetch(url, options = {}) {
let res = await doFetch(token);
if (res.status === 401 && getRefreshToken()) {
if (res.status === 401 && token && getRefreshToken()) {
let newToken;
try {
const newToken = await refreshAccessToken();
res = await doFetch(newToken);
} catch {
clearTokens();
if (onSessionExpired) onSessionExpired();
throw new Error("Session expired");
newToken = await refreshAccessToken(token);
} catch (e) {
if (e instanceof SessionExpiredError) {
expireSession();
throw e;
}
return res;
}
res = await doFetch(newToken);
}
return res;
@@ -88,33 +210,44 @@ export async function apiFetch(url, options = {}) {
/**
* login/register — неавторизованные эндпоинты, без apiFetch (нет токена на входе).
* Обе бросают Error с сообщением от сервера или переданным fallback-текстом.
* Бросают ApiError (status, message с сервера); вызывающий код показывает
* текст через describeApiError.
*/
export async function login(loginValue, password, fallbackErrorMessage) {
export async function login(loginValue, password) {
const res = await fetch(`${API_URL}/api/v1/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ login: loginValue, password }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.message || fallbackErrorMessage);
}
if (!res.ok) throw await readApiError(res);
return res.json(); // { token, refreshToken, user }
}
export async function register(name, loginValue, password, fallbackErrorMessage) {
export async function register(name, loginValue, password) {
const res = await fetch(`${API_URL}/api/v1/auth/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, login: loginValue, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || fallbackErrorMessage);
return data;
if (!res.ok) throw await readApiError(res);
return res.json().catch(() => ({})); // { token, refreshToken, user }
}
export { getAccessToken, getRefreshToken, saveTokens, clearTokens };
/**
* POST /auth/logout — отзывает refresh-токен на сервере. Без этого
* украденный refresh-токен жил бы ещё 7 дней после выхода. Результат не
* важен: локальная сессия очищается в любом случае.
*/
export function revokeRefreshToken(refreshToken = getRefreshToken()) {
if (!refreshToken) return;
fetch(`${API_URL}/api/v1/auth/logout`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }),
keepalive: true,
}).catch(() => {});
}
export { getAccessToken, getRefreshToken, saveTokens, clearTokens, TOKEN_KEY };

147
src/api/apiClient.test.js Normal file
View File

@@ -0,0 +1,147 @@
import {
apiFetch,
getTokenExpiry,
isTokenExpiring,
refreshAccessToken,
SessionExpiredError,
setOnSessionExpired,
} from "./apiClient";
/** JWT без подписи — клиенту нужен только payload.exp. */
function jwt(expSecondsFromNow) {
const payload = { sub: "user", exp: Math.floor(Date.now() / 1000) + expSecondsFromNow };
const encode = (obj) => btoa(JSON.stringify(obj)).replace(/=+$/, "");
return `${encode({ alg: "HS256" })}.${encode(payload)}.sig`;
}
function response(status, body) {
return {
status,
ok: status >= 200 && status < 300,
headers: { get: () => null },
json: async () => body,
};
}
const FRESH = jwt(15 * 60);
const REFRESH = `uuid.${jwt(7 * 24 * 3600)}`;
beforeEach(() => {
localStorage.clear();
global.fetch = jest.fn();
setOnSessionExpired(null);
});
describe("getTokenExpiry", () => {
it("читает exp у access-токена и у refresh-токена вида {uuid}.{jwt}", () => {
expect(getTokenExpiry(FRESH)).toBeGreaterThan(Date.now());
expect(getTokenExpiry(REFRESH)).toBeGreaterThan(Date.now() + 6 * 24 * 3600 * 1000);
});
it("не JWT — null, а не исключение", () => {
expect(getTokenExpiry("garbage")).toBeNull();
expect(getTokenExpiry(null)).toBeNull();
});
it("истекающий токен считается истекающим заранее", () => {
expect(isTokenExpiring(jwt(10))).toBe(true);
expect(isTokenExpiring(FRESH)).toBe(false);
});
});
describe("refreshAccessToken", () => {
it("параллельные вызовы делают один POST /auth/refresh (refresh-токен одноразовый)", async () => {
localStorage.setItem("token", jwt(-10));
localStorage.setItem("refreshToken", REFRESH);
const newAccess = jwt(900);
global.fetch.mockResolvedValue(response(200, { token: newAccess, refreshToken: `uuid2.${jwt(3600)}` }));
const [a, b, c] = await Promise.all([refreshAccessToken(), refreshAccessToken(), refreshAccessToken()]);
expect(global.fetch).toHaveBeenCalledTimes(1);
expect([a, b, c]).toEqual([newAccess, newAccess, newAccess]);
expect(localStorage.getItem("token")).toBe(newAccess);
});
it("401 на refresh — SessionExpiredError", async () => {
localStorage.setItem("token", jwt(-10));
localStorage.setItem("refreshToken", REFRESH);
global.fetch.mockResolvedValue(response(401, { message: "Unauthorized" }));
await expect(refreshAccessToken()).rejects.toBeInstanceOf(SessionExpiredError);
});
it("истёкший refresh-токен не отправляется на сервер", async () => {
localStorage.setItem("token", jwt(-10));
localStorage.setItem("refreshToken", `uuid.${jwt(-60)}`);
await expect(refreshAccessToken()).rejects.toBeInstanceOf(SessionExpiredError);
expect(global.fetch).not.toHaveBeenCalled();
});
});
describe("apiFetch", () => {
it("на 401 обновляет токен один раз для всех параллельных запросов и повторяет их", async () => {
const stale = jwt(600);
const fresh = jwt(900);
localStorage.setItem("token", stale);
localStorage.setItem("refreshToken", REFRESH);
global.fetch.mockImplementation(async (url, init) => {
if (url.endsWith("/api/v1/auth/refresh")) {
return response(200, { token: fresh, refreshToken: `uuid2.${jwt(3600)}` });
}
const auth = init?.headers?.Authorization;
return auth === `Bearer ${fresh}` ? response(200, { ok: true }) : response(401, {});
});
const results = await Promise.all([apiFetch("http://api/a"), apiFetch("http://api/b")]);
expect(results.map((r) => r.status)).toEqual([200, 200]);
const refreshCalls = global.fetch.mock.calls.filter(([url]) => url.endsWith("/auth/refresh"));
expect(refreshCalls).toHaveLength(1);
});
it("refresh отклонён — сессия очищается и вызывается onSessionExpired", async () => {
localStorage.setItem("token", FRESH);
localStorage.setItem("refreshToken", REFRESH);
localStorage.setItem("user", "{}");
const onExpired = jest.fn();
setOnSessionExpired(onExpired);
global.fetch.mockImplementation(async (url) =>
url.endsWith("/auth/refresh") ? response(401, {}) : response(401, {}));
await expect(apiFetch("http://api/a")).rejects.toBeInstanceOf(SessionExpiredError);
expect(onExpired).toHaveBeenCalledTimes(1);
expect(localStorage.getItem("token")).toBeNull();
expect(localStorage.getItem("user")).toBeNull();
});
it("сбой сети или 5xx на refresh не разлогинивает: возвращается исходный 401", async () => {
localStorage.setItem("token", FRESH);
localStorage.setItem("refreshToken", REFRESH);
global.fetch.mockImplementation(async (url) =>
url.endsWith("/auth/refresh") ? response(503, {}) : response(401, {}));
const res = await apiFetch("http://api/a");
expect(res.status).toBe(401);
expect(localStorage.getItem("token")).toBe(FRESH);
expect(localStorage.getItem("refreshToken")).toBe(REFRESH);
});
it("истекающий токен обновляется до запроса (публичные GET не отвечают 401)", async () => {
const fresh = jwt(900);
localStorage.setItem("token", jwt(5));
localStorage.setItem("refreshToken", REFRESH);
global.fetch.mockImplementation(async (url) =>
url.endsWith("/auth/refresh")
? response(200, { token: fresh, refreshToken: `uuid2.${jwt(3600)}` })
: response(200, []));
await apiFetch("http://api/posts");
const [, init] = global.fetch.mock.calls.find(([url]) => url === "http://api/posts");
expect(init.headers.Authorization).toBe(`Bearer ${fresh}`);
});
});

96
src/api/apiErrors.js Normal file
View File

@@ -0,0 +1,96 @@
// src/api/apiErrors.js
import i18n from "../i18n";
/**
* Ошибка REST-запроса к бэкенду.
*
* Бэкенд отвечает в формате ErrorResponse
* {timestamp, status, error, message, path, details}; /auth/login и
* /auth/register — 400 {message}; фильтр безопасности — 401/403 {message}.
* Здесь всё это сводится к одному объекту, чтобы UI не разбирал тело сам.
*/
export class ApiError extends Error {
constructor(status, { code = null, message = "", details = null, retryAfterSeconds = null } = {}) {
super(message || `HTTP ${status}`);
this.name = "ApiError";
this.status = status;
this.code = code;
this.details = details;
this.retryAfterSeconds = retryAfterSeconds;
// Было ли сообщение прислано сервером (а не собрано из статуса)
this.serverMessage = message || "";
}
}
/**
* Retry-After бывает числом секунд или HTTP-датой. Заголовок доступен
* только если бэкенд отдаёт его в Access-Control-Expose-Headers (иначе при
* кросс-доменном запросе браузер его прячет) — тогда вернётся null.
*/
export function parseRetryAfter(value, now = Date.now()) {
if (!value) return null;
const trimmed = String(value).trim();
if (/^\d+$/.test(trimmed)) return Number(trimmed);
const date = Date.parse(trimmed);
if (Number.isNaN(date)) return null;
return Math.max(0, Math.ceil((date - now) / 1000));
}
/** Читает тело ошибки и собирает ApiError. Тело может быть пустым или не JSON. */
export async function readApiError(res) {
let body = null;
try {
body = await res.json();
} catch {
body = null;
}
return new ApiError(res.status, {
code: typeof body?.error === "string" ? body.error : null,
message: typeof body?.message === "string" ? body.message : "",
details: body?.details ?? null,
retryAfterSeconds: parseRetryAfter(res.headers?.get?.("Retry-After")),
});
}
/** Бросает ApiError, если ответ не 2xx; иначе возвращает сам ответ. */
export async function ensureOk(res) {
if (!res.ok) throw await readApiError(res);
return res;
}
export function isRateLimited(err) {
return err?.status === 429;
}
/**
* Текст ошибки для пользователя.
*
* - 429 — «слишком много попыток, повторите через N мин» (без автоповтора:
* повтор в цикле только продлил бы блокировку);
* - 413 — файл больше лимита бэкенда;
* - сбой сети (fetch бросил TypeError) — «нет связи»;
* - 400/404/409/422 — сообщение бэкенда (оно на русском и по делу);
* - остальное (5xx и т.п.) — переданный fallback.
*/
export function describeApiError(err, fallback) {
const t = i18n.t.bind(i18n);
if (!err) return fallback || t("errors.unknown");
if (err.status === 429) {
const seconds = err.retryAfterSeconds;
if (seconds && seconds > 0) {
return seconds >= 60
? t("errors.tooManyRequestsMinutes", { minutes: Math.ceil(seconds / 60) })
: t("errors.tooManyRequestsSeconds", { seconds });
}
return err.serverMessage || t("errors.tooManyRequests");
}
if (err.status === 413) return t("errors.payloadTooLarge");
if (err instanceof TypeError || err.name === "TypeError") return t("errors.network");
if (err instanceof ApiError) {
if (err.status >= 400 && err.status < 500 && err.serverMessage) return err.serverMessage;
return fallback || t("errors.unknown");
}
return err.message || fallback || t("errors.unknown");
}

30
src/api/phoneApi.js Normal file
View 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;
}

12
src/api/searchApi.js Normal file
View File

@@ -0,0 +1,12 @@
import { API_URL } from "../config/authConstants";
/**
* GET /api/v1/posts/search/suggest?q — подсказки для последнего слова строки
* поиска («потерян барс» → ["барсетка", "барсик"]). Эндпоинт публичный.
*/
export async function getSearchSuggestions(query, signal) {
const params = new URLSearchParams({ q: query });
const res = await fetch(`${API_URL}/api/v1/posts/search/suggest?${params}`, { signal });
if (!res.ok) throw new Error(`Error ${res.status}`);
return res.json();
}

BIN
src/assets/chat-bg-dark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 811 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 388 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 811 KiB

View File

@@ -1,15 +1,23 @@
import { useState, useEffect, useRef } from 'react';
import { trackAdClick } from '../hooks/useAdClickTracking';
import { useAdImpressionTracking } from '../hooks/useAdImpressionTracking';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { trackAdClick, trackAdImpression } from '../api/adsApi';
import { useAdViewability } from '../hooks/useAdViewability';
import { toSafeHttpUrl } from '../utils/safeUrl';
const SKIP_DELAY_SECONDS = 5;
export default function AdCard({ ad, onClose }) {
const { t } = useTranslation();
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const cardRef = useRef(null);
const videoRef = useRef(null);
// targetUrl приходит из данных: открываем только абсолютный http(s),
// "javascript:"/"data:" и относительные ссылки отбрасываем.
const targetUrl = toSafeHttpUrl(ad.targetUrl);
useAdImpressionTracking(cardRef, ad.advertisingId);
// Показ засчитывается, когда ≥ 50% баннера видно ≥ 1 с (а не при выдаче).
const handleViewable = useCallback(() => trackAdImpression(ad), [ad]);
useAdViewability(cardRef, handleViewable);
useEffect(() => {
if (remaining <= 0) return;
@@ -43,43 +51,56 @@ export default function AdCard({ ad, onClose }) {
return () => observer.disconnect();
}, []);
const handleClick = () => {
trackAdClick(ad.advertisingId);
window.open(ad.targetUrl, '_blank', 'noopener,noreferrer');
};
// Переход делает сам <a target="_blank" rel="noopener noreferrer"> — клик
// только учитываем. Так ссылка работает с клавиатуры и средней кнопкой мыши.
const handleClick = () => trackAdClick(ad);
const media = ad.type === 'VIDEO' ? (
<video
ref={videoRef}
src={ad.mediaUrl}
className="ad-card__media"
muted
autoPlay
playsInline
loop
preload="metadata"
aria-label={t('ads.label')}
/>
) : (
<img
src={ad.mediaUrl}
alt={t('ads.label')}
className="ad-card__media"
decoding="async"
/>
);
return (
<div ref={cardRef} className="ad-card">
<span className="ad-card__label">Реклама</span>
<span className="ad-card__label">{t('ads.label')}</span>
{ad.type === 'VIDEO' ? (
<video
ref={videoRef}
src={ad.mediaUrl}
className="ad-card__media"
muted
autoPlay
playsInline
loop
preload="auto"
{targetUrl ? (
<a
href={targetUrl}
target="_blank"
rel="noopener noreferrer sponsored"
className="ad-card__link"
onClick={handleClick}
/>
) : (
<img
src={ad.mediaUrl}
alt="Реклама"
className="ad-card__media"
onClick={handleClick}
/>
)}
onAuxClick={handleClick}
aria-label={t('ads.openLink')}
>
{media}
</a>
) : media}
{remaining > 0 ? (
<span className="ad-card__skip-timer">Закрыть через {remaining}с</span>
<span className="ad-card__skip-timer">{t('ads.closeIn', { seconds: remaining })}</span>
) : (
<button className="ad-card__close" onClick={onClose} aria-label="Закрыть рекламу">
<button type="button" className="ad-card__close" onClick={onClose} aria-label={t('ads.close')}>
✕
</button>
)}
</div>
);
}
}

View File

@@ -1,13 +1,13 @@
import { useEffect, useRef, useState } from 'react';
import { API_URL } from '../config/authConstants';
import { getAccessToken } from '../api/apiClient';
import { normalizeMediaUrl } from '../api/adsApi';
import { getNextAd } from '../api/adsApi';
import AdCard from './AdCard';
export default function AdSlot() {
const slotRef = useRef(null);
const [ad, setAd] = useState(null);
const [closed, setClosed] = useState(false);
// Показывать нечего (204 или ошибка) — слот убирается из ленты целиком
const [empty, setEmpty] = useState(false);
useEffect(() => {
if (closed) return;
@@ -15,28 +15,24 @@ export default function AdSlot() {
if (!node) return;
let cancelled = false;
const controller = new AbortController();
const observer = new IntersectionObserver(
([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
const token = getAccessToken();
fetch(`${API_URL}/api/ads/next`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
.then((res) => {
// 204 No Content — свободных объявлений нет, оставляем пустой слот
if (res.status === 204) return null;
if (!res.ok) throw new Error(`Error ${res.status}`);
return res.json();
})
// Выдача — ещё не показ: показ засчитывается в AdCard, когда
// баннер реально виден (useAdViewability).
getNextAd(controller.signal)
.then((data) => {
if (!cancelled && data) {
if (data.mediaUrl) data.mediaUrl = normalizeMediaUrl(data.mediaUrl);
setAd(data);
}
if (cancelled) return;
// null — 204 (нет кандидатов, лимит, пауза между показами) или 429
if (!data) setEmpty(true);
else setAd(data);
})
.catch(() => {});
.catch(() => {
if (!cancelled) setEmpty(true);
});
},
{ rootMargin: '200px' }
);
@@ -44,13 +40,16 @@ export default function AdSlot() {
observer.observe(node);
return () => {
cancelled = true;
controller.abort();
observer.disconnect();
};
}, [closed]);
const handleClose = () => setClosed(true);
if (closed) return null;
// Слот грузится заранее (rootMargin 200px), т.е. ещё ниже экрана —
// его исчезновение не сдвигает видимую часть ленты
if (closed || empty) return null;
if (ad) {
return (

View File

@@ -0,0 +1,215 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import ClearableField from "./ClearableField";
import { geocodeText, resolveSuggestion, suggestAddresses } from "../utils/yandexGeo";
const DEBOUNCE_MS = 250;
const MIN_CHARS = 3;
/**
* AddressAutocomplete — поле адреса с подсказками, как на Яндекс Картах.
*
* @param {string} value — текст в поле
* @param {function} onChange — ручной ввод: (text) => void
* @param {function} onSelect — выбран адрес с точкой: ({ address, coords: [lat, lng] }) => void
* @param {function} getCenter — () => [lat, lng] | null, центр карты для приоритета подсказок
* @param {string} placeholder
* @param {boolean} invalid — подсветить поле как ошибочное
*/
export default function AddressAutocomplete({ value, onChange, onSelect, getCenter, placeholder, invalid }) {
const { t } = useTranslation();
const [items, setItems] = useState([]);
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const [searching, setSearching] = useState(false);
const [message, setMessage] = useState("");
// Подсказки ищем только на ввод пользователя, а не когда текст поменяла карта
const typedRef = useRef(false);
const abortRef = useRef(null);
const cancelRequest = () => {
abortRef.current?.abort();
abortRef.current = null;
};
const newSignal = () => {
cancelRequest();
abortRef.current = new AbortController();
return abortRef.current.signal;
};
useEffect(() => cancelRequest, []);
useEffect(() => {
if (!typedRef.current) return;
const text = value.trim();
if (text.length < MIN_CHARS) {
cancelRequest();
setItems([]);
setSearching(false);
setMessage("");
return;
}
const timer = setTimeout(() => {
const signal = newSignal();
setSearching(true);
setMessage("");
suggestAddresses(text, { center: getCenter?.(), signal })
.then(found => {
if (signal.aborted) return;
setItems(found);
setActive(-1);
setOpen(true);
setMessage(found.length ? "" : t("post.addressNotFound"));
})
.catch(e => {
if (signal.aborted || e.name === "AbortError") return;
setItems([]);
setMessage(t("post.addressSearchFailed"));
})
.finally(() => {
if (!signal.aborted) setSearching(false);
});
}, DEBOUNCE_MS);
return () => clearTimeout(timer);
// getCenter и t стабильны по смыслу; перезапускаем только на смену текста
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
const close = () => {
setOpen(false);
setActive(-1);
};
const choose = (item) => {
typedRef.current = false;
close();
setItems([]);
onChange(item.address);
const signal = newSignal();
setSearching(true);
setMessage("");
resolveSuggestion(item, { signal })
.then(res => {
if (signal.aborted) return;
if (res) onSelect(res);
else setMessage(t("post.addressNotFound"));
})
.catch(e => {
if (signal.aborted || e.name === "AbortError") return;
setMessage(t("post.addressSearchFailed"));
})
.finally(() => {
if (!signal.aborted) setSearching(false);
});
};
/** Enter без выбора подсказки — ищем введённый текст как есть. */
const searchTyped = () => {
const text = value.trim();
if (!text) return;
typedRef.current = false;
close();
const signal = newSignal();
setSearching(true);
setMessage("");
geocodeText(text, { center: getCenter?.(), signal })
.then(([found]) => {
if (signal.aborted) return;
if (found) onSelect({ address: found.address, coords: found.coords });
else setMessage(t("post.addressNotFound"));
})
.catch(e => {
if (signal.aborted || e.name === "AbortError") return;
setMessage(t("post.addressSearchFailed"));
})
.finally(() => {
if (!signal.aborted) setSearching(false);
});
};
const onKeyDown = (e) => {
if (e.key === "ArrowDown" && items.length) {
e.preventDefault();
setOpen(true);
setActive(i => (i + 1) % items.length);
} else if (e.key === "ArrowUp" && items.length) {
e.preventDefault();
setOpen(true);
setActive(i => (i <= 0 ? items.length - 1 : i - 1));
} else if (e.key === "Enter") {
e.preventDefault();
if (open && active >= 0 && items[active]) choose(items[active]);
else searchTyped();
} else if (e.key === "Escape" && open) {
e.preventDefault();
close();
}
};
const showList = open && items.length > 0;
return (
<div className="f-addr">
<ClearableField
onClear={() => {
typedRef.current = false;
cancelRequest();
setItems([]);
setMessage("");
setSearching(false);
onChange("");
}}
visible={!!value}
>
<input
className={`f-m-field${invalid ? " err" : ""}`}
type="text"
placeholder={placeholder}
value={value}
autoComplete="off"
role="combobox"
aria-expanded={showList}
aria-autocomplete="list"
aria-controls="f-addr-list"
aria-activedescendant={showList && active >= 0 ? `f-addr-opt-${active}` : undefined}
onChange={e => {
typedRef.current = true;
onChange(e.target.value);
}}
onFocus={() => items.length && setOpen(true)}
onBlur={close}
onKeyDown={onKeyDown}
/>
</ClearableField>
{searching && <div className="f-addr-spinner" aria-hidden="true" />}
{showList && (
<ul className="f-addr-list" id="f-addr-list" role="listbox">
{items.map((item, i) => (
<li
key={`${item.address}-${i}`}
id={`f-addr-opt-${i}`}
role="option"
aria-selected={i === active}
className={`f-addr-item${i === active ? " active" : ""}`}
// mousedown, а не click: иначе blur поля закроет список раньше клика
onMouseDown={e => {
e.preventDefault();
choose(item);
}}
onMouseEnter={() => setActive(i)}
>
<span className="f-addr-title">{item.title}</span>
{item.subtitle && <span className="f-addr-sub">{item.subtitle}</span>}
</li>
))}
</ul>
)}
{message && <p className="f-hint">{message}</p>}
</div>
);
}

View File

@@ -4,6 +4,8 @@ import { useTranslation } from 'react-i18next';
import CloseIcon from "./icons/CloseIcon";
import { useAuthContext } from "../context/AuthContext";
import { login as apiLogin, register as apiRegister } from "../api/apiClient";
import { describeApiError } from "../api/apiErrors";
import { validatePassword } from "../utils/passwordPolicy";
/**
* AuthModal — модальное окно входа и регистрации прямо на странице ленты.
@@ -63,13 +65,13 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
setLoading(true); setError("");
try {
const { token, refreshToken, user } = await apiLogin(
login, password, t('auth.invalidCredentials')
);
const { token, refreshToken, user } = await apiLogin(login, password);
saveAuth(user, token, refreshToken);
onClose();
} catch (err) {
setError(err.message);
// 400 — неверные данные (текст с сервера), 429 — лимит попыток или
// блокировка аккаунта на 15 минут после 10 неудачных входов
setError(describeApiError(err, t('auth.invalidCredentials')));
} finally {
setLoading(false);
}
@@ -85,7 +87,8 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
placeholder={t('auth.yourLogin')}
value={login}
onChange={e => { setLogin(e.target.value); setError(""); }}
autoComplete="off"
autoComplete="username"
autoCapitalize="none"
/>
</div>
@@ -95,6 +98,7 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
className="f-m-field"
type="password"
placeholder={t('auth.yourPassword')}
autoComplete="current-password"
value={password}
onChange={e => { setPassword(e.target.value); setError(""); }}
/>
@@ -106,7 +110,7 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
<p style={{textAlign: "center", marginTop: 14, color: "var(--muted)", fontSize: ".85rem"}}>
{t('auth.noAccount')}{" "}
<button onClick={onSwitch}
<button type="button" onClick={onSwitch}
style={{background: "none", border: "none", color: "var(--teal)", cursor: "pointer", fontWeight: 700, fontSize: ".85rem", fontFamily: "var(--font)",}}
>
{t('auth.register')}
@@ -136,7 +140,8 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
if (!form.name.trim()) e.name = t('auth.validateNameRequired');
if (!form.login.trim()) e.login = t('auth.validateLoginRequired');
else if (form.login.length < 3) e.login = t('auth.loginMinChars');
if (form.password.length < 6) e.password = t('auth.validatePasswordMin');
const passwordError = validatePassword(form.password);
if (passwordError) e.password = passwordError;
if (form.password !== form.password2) e.password2 = t('auth.validatePasswordMatch');
setErrors(e);
return !Object.keys(e).length;
@@ -147,21 +152,24 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
if (!validate()) return;
setLoading(true); setError("");
let registered = false;
try {
await apiRegister(form.name, form.login, form.password, t('auth.registrationError'));
let session;
try {
session = await apiLogin(form.login, form.password, t('auth.autoLoginFailed'));
} catch {
throw new Error(t('auth.accountCreatedLoginManually'));
// Регистрация сразу возвращает {token, refreshToken, user}. Отдельный
// вход нужен только если бэкенд их не прислал — лишний запрос к
// /auth/login тратил бы лимит попыток входа.
let session = await apiRegister(form.name, form.login, form.password);
registered = true;
if (!session?.token) {
session = await apiLogin(form.login, form.password);
}
const { token, refreshToken, user } = session;
saveAuth(user, token, refreshToken);
onClose();
} catch (err) {
setError(err.message);
setError(registered
? t('auth.accountCreatedLoginManually')
: describeApiError(err, t('auth.registrationError')));
} finally {
setLoading(false);
}
@@ -187,6 +195,8 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.login ? " err" : ""}`}
type="text"
placeholder={t('auth.loginPlaceholder')}
autoComplete="username"
autoCapitalize="none"
value={form.login}
onChange={e => setField("login", e.target.value)}
/>
@@ -200,6 +210,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.password ? " err" : ""}`}
type="password"
placeholder={t('auth.passwordMinShort')}
autoComplete="new-password"
value={form.password}
onChange={e => setField("password", e.target.value)}
/>
@@ -211,6 +222,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
className={`f-m-field${errors.password2 ? " err" : ""}`}
type="password"
placeholder={t('auth.repeatPlaceholder')}
autoComplete="new-password"
value={form.password2}
onChange={e => setField("password2", e.target.value)}
/>
@@ -224,7 +236,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
<p style={{textAlign: "center", marginTop: 14, color: "var(--muted)", fontSize: ".85rem"}}>
{t('auth.hasAccount')}{" "}
<button onClick={onSwitch}
<button type="button" onClick={onSwitch}
style={{background: "none", border: "none", color: "var(--teal)", cursor: "pointer", fontWeight: 700, fontSize: ".85rem", fontFamily: "var(--font)",}}>
{t('auth.loginLink')}
</button>

View File

@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useMemo } from "react";
import { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useCityOptions } from "../hooks/useCityOptions";
/**
* CityFilter — мультиселект городов с поиском и свободным вводом.
@@ -27,18 +28,7 @@ export default function CityFilter({ cities, value, onChange }) {
return () => document.removeEventListener("mousedown", onDocMouseDown);
}, [open]);
const normalizedQuery = query.trim().toLowerCase();
// Города, совпадающие с введённым текстом (выбранные помечаются галочкой)
const options = useMemo(() => {
const q = normalizedQuery;
return cities.filter(c => c && (!q || c.toLowerCase().includes(q)));
}, [cities, normalizedQuery]);
// Свободный ввод доступен, если введён текст, которого нет ни в списке, ни в выбранных
const canAddCustom = normalizedQuery.length > 0 &&
!value.some(c => c.toLowerCase() === normalizedQuery) &&
!cities.some(c => c.toLowerCase() === normalizedQuery);
const { options, typedCity } = useCityOptions(cities, value, query);
const toggle = (city) => {
if (value.includes(city)) {
@@ -50,20 +40,19 @@ export default function CityFilter({ cities, value, onChange }) {
inputRef.current?.focus();
};
const addCustom = () => {
const city = query.trim();
if (city && !value.includes(city)) {
onChange([...value, city]);
}
// Города нет в списке — объявлений там нет, но фильтр всё равно применяем:
// лента покажет «В этом городе нет объявлений»
const applyTyped = () => {
onChange([...value, typedCity]);
setQuery("");
inputRef.current?.focus();
setOpen(false);
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
if (canAddCustom) {
addCustom();
if (typedCity) {
applyTyped();
} else if (options.length) {
toggle(options[0]);
}
@@ -148,23 +137,10 @@ export default function CityFilter({ cities, value, onChange }) {
{open && (
<div className="f-city-ms-dropdown">
{options.length === 0 && !canAddCustom && (
{options.length === 0 && (
<div className="f-city-ms-empty">{t('feed.filterCitiesEmpty')}</div>
)}
{canAddCustom && (
<button type="button" className="f-city-ms-option f-city-ms-add"
onClick={() => {
addCustom();
setOpen(false);
}}>
<span className="f-city-ms-check">+</span>
<span className="f-city-ms-label">
{t('feed.filterCitiesAdd', { city: query.trim() })}
</span>
</button>
)}
{options.map(city => {
const selected = value.includes(city);
return (

View File

@@ -17,30 +17,52 @@ export default function DateCalendarPopup({ date, onClose, anchorRef }) {
const [month, setMonth] = useState(isValidDate ? selectedDate.getMonth() : new Date().getMonth());
// Двухпроходное позиционирование:
// 1) сразу после монтирования попап невидим (opacity: 0), но уже в DOM —
// 1) сразу после монтирования попап невидим, но уже в DOM —
// нужно, чтобы измерить его реальные width/height.
// 2) как только размеры известны — пересчитываем координаты так, чтобы
// попап открывался влево-вверх от якоря, и показываем (opacity: 1).
// 2) как только размеры известны — ставим его влево-вверх от якоря
// (или вниз, если сверху не хватает места) и показываем.
// Координаты — относительно окна (position: fixed): лента листается во
// внутреннем контейнере, и window.scrollY тут не помогает.
useLayoutEffect(() => {
if (!anchorRef?.current || !ref.current) return;
const anchorRect = anchorRef.current.getBoundingClientRect();
const popupRect = ref.current.getBoundingClientRect();
const GAP = 4;
setCoords({
top: anchorRect.top + window.scrollY - popupRect.height - 4,
left: anchorRect.right + window.scrollX - popupRect.width,
});
const above = anchorRect.top - popupRect.height - GAP;
const top = above >= GAP ? above : anchorRect.bottom + GAP;
const left = Math.min(
Math.max(GAP, anchorRect.right - popupRect.width),
window.innerWidth - popupRect.width - GAP
);
setCoords({ top, left });
}, [anchorRef, month, year]); // пересчитываем и при смене месяца — высота грид может немного плавать
// Закрываем при клике/тапе вне попапа и кнопки, при любой прокрутке
// (ленты, окна) и при изменении размера окна — иначе попап «отрывается»
// от кнопки и висит поверх ленты.
useEffect(() => {
const handler = (e) => {
const onPointerDown = (e) => {
const clickedAnchor = anchorRef?.current?.contains(e.target);
const clickedPopup = ref.current?.contains(e.target);
if (!clickedAnchor && !clickedPopup) onClose();
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
const onScroll = (e) => {
if (ref.current?.contains(e.target)) return;
onClose();
};
// capture: срабатывает, даже если кто-то по пути остановил всплытие,
// а scroll внутренних контейнеров до document не всплывает вовсе.
document.addEventListener("pointerdown", onPointerDown, true);
document.addEventListener("scroll", onScroll, true);
window.addEventListener("resize", onClose);
return () => {
document.removeEventListener("pointerdown", onPointerDown, true);
document.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", onClose);
};
}, [onClose, anchorRef]);
const goToPrevMonth = () => {
@@ -79,8 +101,11 @@ export default function DateCalendarPopup({ date, onClose, anchorRef }) {
<div
className="f-date-calendar"
ref={ref}
// События из портала всплывают по дереву React: без этого клик по
// календарю переключал бы кнопку даты и открывал карточку.
onClick={e => e.stopPropagation()}
style={{
position: "absolute",
position: "fixed",
top: coords?.top ?? 0,
left: coords?.left ?? 0,
zIndex: 1000,

View File

@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { openExternalUrl } from "../utils/safeUrl";
const SKIP_DELAY_SECONDS = 5;
@@ -18,6 +19,26 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const [soundOn, setSoundOn] = useState(false);
const videoRef = useRef(null);
const closeRef = useRef(null);
const canClose = remaining <= 0;
// Фон под оверлеем не скроллится (на iOS иначе «уезжает» лента)
useEffect(() => {
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => { document.body.style.overflow = prev; };
}, []);
// Esc закрывает, как только появилась кнопка закрытия; фокус — на неё
useEffect(() => {
if (!canClose) return;
closeRef.current?.focus();
const onKey = (e) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [canClose, onClose]);
useEffect(() => {
if (remaining <= 0) return;
@@ -54,9 +75,8 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
const handleVideoClick = () => {
videoRef.current?.play().catch(() => {});
if (ad.targetUrl) {
window.open(ad.targetUrl, "_blank", "noopener,noreferrer");
}
// Только абсолютный http(s): targetUrl — данные с сервера
openExternalUrl(ad.targetUrl);
};
const handleToggleSound = (e) => {
@@ -70,7 +90,7 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
};
return (
<div className="fs-ad-overlay">
<div className="fs-ad-overlay" role="dialog" aria-modal="true" aria-label={t('fullscreenAd.label')}>
<span className="fs-ad-label">{t('fullscreenAd.label')}</span>
<video
ref={(node) => {
@@ -95,12 +115,13 @@ export default function FullscreenAdOverlay({ ad, onClose }) {
>
{soundOn ? "🔊" : "🔇"}
</button>
{remaining > 0 ? (
{!canClose ? (
<span className="fs-ad-skip-timer">
{t('fullscreenAd.closeIn', { seconds: remaining })}
</span>
) : (
<button
ref={closeRef}
type="button"
className="fs-ad-close"
onClick={onClose}

View 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();
});

View 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>
);
}

View 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>
);
}

View File

@@ -1,122 +0,0 @@
import { useState, useCallback, useEffect, useRef, useMemo } from "react";
import { useTranslation } from 'react-i18next';
import CloseIcon from "./icons/CloseIcon";
import Toast from "./Toast";
import { getImageUrl } from "../config/authConstants";
import { useContactSeller } from "../hooks/useContactSeller";
import { useAuthContext } from "../context/AuthContext";
export default function ImageViewer({ images, initialIndex = 0, onClose, postData }) {
const { t } = useTranslation();
const [index, setIndex] = useState(initialIndex);
const touchStart = useRef(null);
const swiped = useRef(false);
const { isAuthenticated } = useAuthContext();
const { contactSeller, error: contactError, clearError } = useContactSeller(postData);
const urls = useMemo(() => images.map(u => getImageUrl(u)), [images]);
const next = useCallback(() => {
setIndex(i => (i + 1) % urls.length);
}, [urls.length]);
const prev = useCallback(() => {
setIndex(i => (i - 1 + urls.length) % urls.length);
}, [urls.length]);
const handleImgClick = useCallback(() => {
next();
}, [next]);
useEffect(() => {
const handleKey = (e) => {
if (e.key === "Escape") onClose();
if (e.key === "ArrowRight") next();
if (e.key === "ArrowLeft") prev();
};
window.addEventListener("keydown", handleKey);
return () => window.removeEventListener("keydown", handleKey);
}, [onClose, next, prev]);
useEffect(() => {
setIndex(initialIndex);
}, [initialIndex]);
const handleTouchStart = useCallback((e) => {
touchStart.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
}, []);
const handleTouchEnd = useCallback((e) => {
if (!touchStart.current) return;
const dx = e.changedTouches[0].clientX - touchStart.current.x;
const dy = e.changedTouches[0].clientY - touchStart.current.y;
const isHorizontal = Math.abs(dx) > Math.abs(dy);
if (isHorizontal && Math.abs(dx) > 50) {
swiped.current = true;
if (dx > 0) prev();
else next();
setTimeout(() => { swiped.current = false; }, 400);
}
touchStart.current = null;
}, [prev, next]);
const handleContact = useCallback(() => {
// Закрываем вьюер перед переходом в чат
contactSeller(onClose);
}, [contactSeller, onClose]);
const showContact = isAuthenticated && postData && !postData.isOwner && postData.status !== 'CLOSED';
if (!urls.length) return null;
return (
<div
className="f-viewer-bg"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
onClick={e => e.target === e.currentTarget && !swiped.current && onClose()}
>
<button type="button" className="f-viewer-close" onClick={onClose} aria-label={t('common.close')}>
<CloseIcon />
</button>
<div className="f-viewer">
<div className="f-viewer-img-wrap" onClick={handleImgClick}>
<img
src={urls[index]}
alt=""
className="f-viewer-img"
/>
</div>
{showContact && (
<button type="button" className="f-viewer-contact" onClick={handleContact}>
{t('postCard.write')}
</button>
)}
{urls.length > 1 && (
<div className="f-viewer-dots">
{urls.map((_, i) => (
<button
type="button"
key={i}
className={`f-viewer-dot${i === index ? " active" : ""}`}
onClick={() => setIndex(i)}
aria-label={t('viewer.goToImage', { number: i + 1 })}
/>
))}
</div>
)}
</div>
{contactError && (
<Toast
message={contactError}
type="error"
onDismiss={clearError}
/>
)}
</div>
);
}

View File

@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { API_URL, getImageUrl } from "../config/authConstants";
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
import { whenYmapsReady } from "../utils/ymapsApi";
import { escapeCssUrl, escapeHtml } from "../utils/escapeHtml";
const MARKER_COLORS = {
LOST: "#ff3b30",
@@ -9,13 +11,13 @@ const MARKER_COLORS = {
FOUND: "#34c759",
};
function createMarkerLayout(color, imageUrl) {
function createMarkerLayout(color, imageUrl, pinId) {
const bgStyle = imageUrl
? `background-image:url('${imageUrl}');background-size:cover;background-position:center;`
? `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};
@@ -40,12 +42,111 @@ function createMarkerLayout(color, imageUrl) {
const FOCUS_ZOOM = 16;
const COORD_MATCH_TOLERANCE = 0.005;
const MAP_CENTER = [55.751574, 37.573856];
const MAP_ZOOM = 11;
const BOUNDS_DEBOUNCE_MS = 400;
const BOUNDS_RETRY_MS = 120;
const MAX_BOUNDS_ATTEMPTS = 25;
export default function MapView({ focusPostId, focusLat, focusLng, onPostClick, onBack }) {
/**
* GET /api/v1/posts/map
*
* Контракт требует границы видимой области карты — без любого из четырёх
* параметров бэкенд отвечает 400. type/category остаются опциональными и
* уезжают тем же запросом.
*/
async function loadMarkers(bounds, type, category) {
const [[minLat, minLng], [maxLat, maxLng]] = bounds;
const params = new URLSearchParams({
minLat: minLat.toString(),
maxLat: maxLat.toString(),
minLng: minLng.toString(),
maxLng: maxLng.toString(),
});
if (type) params.append("type", type);
if (category) params.append("category", category);
const response = await fetch(`${API_URL}/api/v1/posts/map?${params.toString()}`);
if (!response.ok) {
throw new Error(`Failed to load markers: ${response.status}`);
}
return response.json();
}
// Ключ для отсечения повторных запросов с одними и теми же границами.
// Нужен, потому что границы меняются и от действий пользователя (pan/zoom),
// и от программной установки центра — иначе на каждое такое изменение
// улетал бы лишний одинаковый запрос.
function boundsKey(bounds) {
return bounds.map(([lat, lng]) => `${lat.toFixed(5)}:${lng.toFixed(5)}`).join("|");
}
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, m.id != null ? String(m.id) : "");
return new window.ymaps.Placemark(
[m.latitude, m.longitude],
// hintContent — свойство метки (не опция) и рендерится как HTML:
// заголовок объявления — пользовательский текст, экранируем.
{ hintContent: escapeHtml(m.title || typeLabel) },
{
iconLayout,
iconImageSize: [40, 40],
iconImageOffset: [-20, -20],
// Без явного iconShape карта не может корректно вычислить
// кликабельную область для кастомного HTML-лейаута —
// маркер рисуется, но клики по нему не срабатывают.
iconShape: {
type: "Circle",
coordinates: [20, 20],
radius: 20,
},
hasBalloon: false,
hasHint: true,
}
);
}
/**
* @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,
focusLng,
type = null,
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:
// иначе смена языка пересоздавала бы карту и все маркеры с нуля.
const tRef = useRef(t);
tRef.current = t;
const mapRef = useRef(null);
const ymapRef = useRef(null);
const userMarkerRef = useRef(null);
const markersRef = useRef(null);
const renderMarkersRef = useRef(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
@@ -53,120 +154,287 @@ export default function MapView({ focusPostId, focusLat, focusLng, onPostClick,
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: их смена не должна пересоздавать карту,
// они просто уезжают вместе с границами в том же самом запросе.
const filtersRef = useRef({ type, category });
filtersRef.current = { type, category };
useEffect(() => {
let map;
const destroyed = { current: false };
let destroyed = false;
let debounceTimer = null;
let boundsRetryTimer = null;
let firstLoadDone = false;
let lastBoundsKey = null;
let requestId = 0;
const subscriptions = [];
const init = async () => {
if (!mapRef.current || destroyed.current) return;
// Перерисовывает маркеры в текущей видимой области и возвращает
// словарь postId -> [lat, lng] для логики фокуса.
const renderMarkers = (markers) => {
const collection = markersRef.current;
const placemarksById = new Map();
if (!collection) return placemarksById;
collection.removeAll();
placemarksRef.current = new Map();
markers.forEach((m) => {
if (m.latitude == null || m.longitude == null) return;
const placemark = createPostPlacemark(m);
collection.add(placemark);
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;
const focusOnPost = (placemarksById) => {
let target = focusPostId != null
? placemarksById.get(String(focusPostId))
: null;
if (!target && Number.isFinite(focusLat) && Number.isFinite(focusLng)) {
let best = null;
let bestDist = Infinity;
placemarksById.forEach((coords) => {
const d =
Math.pow(coords[0] - focusLat, 2) +
Math.pow(coords[1] - focusLng, 2);
if (d < bestDist) {
bestDist = d;
best = coords;
}
});
if (best && bestDist < COORD_MATCH_TOLERANCE * COORD_MATCH_TOLERANCE) {
target = best;
}
}
if (target) {
map.setCenter(target, FOCUS_ZOOM);
}
};
const load = async (bounds, isInitial) => {
if (isInitial) setLoading(true);
const request = ++requestId;
try {
const res = await fetch(`${API_URL}/api/v1/posts/map`);
if (!res.ok) throw new Error("Failed to fetch map markers");
const markers = await res.json();
const markers = await loadMarkers(
bounds,
filtersRef.current.type,
filtersRef.current.category
);
if (destroyed || request !== requestId) return;
if (destroyed.current) return;
const placemarksById = renderMarkers(Array.isArray(markers) ? markers : []);
if (isInitial) focusOnPost(placemarksById);
} catch (e) {
// Фоновая догрузка не должна перекрывать рабочую карту ошибкой —
// показываем её только на первом запросе.
if (!destroyed && request === requestId && isInitial) setError(e.message);
} finally {
if (!destroyed && request === requestId) setLoading(false);
// Спиннер снимаем в любом случае: иначе при пустых границах карта
// навсегда останется закрыта оверлеем загрузки.
if (!destroyed && isInitial) {
firstLoadDone = true;
setLoading(false);
}
}
};
const requestMarkers = (bounds, isInitial) => {
if (destroyed) return;
if (!bounds || bounds.length < 2) return;
const key = boundsKey(bounds);
if (key === lastBoundsKey) return;
lastBoundsKey = key;
load(bounds, isInitial);
};
// Перемещение/зум: перезапрашиваем маркеры, но не на каждый пиксель.
const scheduleMarkers = () => {
if (destroyed) return;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
requestMarkers(readBounds(), false);
}, BOUNDS_DEBOUNCE_MS);
};
// Безопасное чтение границ: до полного рендера карты getBounds()
// возвращает null/undefined или координаты-заглушки.
const readBounds = () => {
if (destroyed || !map) return null;
const bounds = map.getBounds();
if (!bounds || bounds.length < 2) return null;
const [[minLat, minLng], [maxLat, maxLng]] = bounds;
if (![minLat, minLng, maxLat, maxLng].every(Number.isFinite)) return null;
return bounds;
};
// Первая загрузка. У ymaps.Map в 2.1 нет события 'load', поэтому
// готовность границ отслеживаем через boundschange (он прилетает уже
// при первом расчёте вьюпорта) + короткий ретрай, если событие не пришло.
const loadInitial = (attempt = 0) => {
if (destroyed || firstLoadDone) return;
const bounds = readBounds();
if (bounds) {
requestMarkers(bounds, true);
return;
}
if (attempt >= MAX_BOUNDS_ATTEMPTS) {
firstLoadDone = true;
setLoading(false);
return;
}
boundsRetryTimer = setTimeout(() => loadInitial(attempt + 1), BOUNDS_RETRY_MS);
};
const init = () => {
if (!mapRef.current || destroyed) return;
try {
const hasFocusCoords = Number.isFinite(focusLat) && Number.isFinite(focusLng);
map = new window.ymaps.Map(mapRef.current, {
center: [55.751574, 37.573856],
zoom: 11,
center: hasFocusCoords ? [focusLat, focusLng] : MAP_CENTER,
zoom: hasFocusCoords ? FOCUS_ZOOM : MAP_ZOOM,
controls: ["zoomControl", "geolocationControl"],
});
ymapRef.current = map;
const placemarksById = new Map();
const collection = new window.ymaps.GeoObjectCollection();
map.geoObjects.add(collection);
markersRef.current = collection;
markers.forEach((m) => {
if (m.latitude == null || m.longitude == null) return;
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 coords = [m.latitude, m.longitude];
const placemark = new window.ymaps.Placemark(
coords,
{},
{
iconLayout,
iconImageSize: [40, 40],
iconImageOffset: [-20, -20],
// Без явного iconShape карта не может корректно вычислить
// кликабельную область для кастомного HTML-лейаута —
// маркер рисуется, но клики по нему не срабатывают.
iconShape: {
type: "Circle",
coordinates: [20, 20],
radius: 20,
},
hasBalloon: false,
hasHint: true,
hintContent: m.title || typeLabel,
}
);
map.geoObjects.add(placemark);
if (m.id != null) {
const postId = String(m.id);
placemarksById.set(postId, { placemark, coords });
placemark.events.add("click", () => {
if (onPostClickRef.current) {
onPostClickRef.current(postId);
}
});
subscriptions.push(map.events.add("boundschange", () => {
if (!firstLoadDone) {
clearTimeout(boundsRetryTimer);
loadInitial();
}
});
scheduleMarkers();
}));
let target = focusPostId != null
? placemarksById.get(String(focusPostId))
: null;
if (!target && Number.isFinite(focusLat) && Number.isFinite(focusLng)) {
let best = null;
let bestDist = Infinity;
placemarksById.forEach((entry) => {
const d =
Math.pow(entry.coords[0] - focusLat, 2) +
Math.pow(entry.coords[1] - focusLng, 2);
if (d < bestDist) {
bestDist = d;
best = entry;
}
});
if (best && bestDist < COORD_MATCH_TOLERANCE * COORD_MATCH_TOLERANCE) {
target = best;
}
}
if (target) {
map.setCenter(target.coords, FOCUS_ZOOM);
} else if (placemarksById.size > 0) {
map.setBounds(
map.geoObjects.getBounds(),
{ checkZoomRange: true, zoomMargin: 40 }
);
}
// Подстраховка на случай, если boundschange не придёт.
loadInitial();
} catch (e) {
if (!destroyed.current) setError(e.message);
} finally {
if (!destroyed.current) setLoading(false);
if (!destroyed) {
setError(e.message);
setLoading(false);
}
}
};
if (window.ymaps?.ready) {
window.ymaps.ready(init);
}
whenYmapsReady()
.then((ymaps) => {
if (destroyed) return;
ymaps.ready(init);
})
.catch((e) => {
// API карт не подгрузился (заблокирован/офлайн/медленный CDN).
// Без этой ветки пользователь смотрел бы в вечный спиннер без ошибки.
if (!destroyed) {
setError(tRef.current("post.mapLoadFailed"));
setLoading(false);
}
console.warn("Yandex Maps API failed to load:", e);
});
return () => {
destroyed.current = true;
destroyed = true;
clearTimeout(debounceTimer);
clearTimeout(boundsRetryTimer);
subscriptions.forEach((sub) => {
try {
map?.events.remove(sub);
} catch (e) {
// карта уже уничтожена — ничего не делаем
}
});
ymapRef.current?.destroy();
ymapRef.current = null;
markersRef.current = null;
renderMarkersRef.current = null;
userMarkerRef.current = null;
};
}, [focusPostId, focusLat, focusLng]);
// Смена фильтров type/category: догружаем маркеры для текущих границ,
// карту при этом не пересоздаём.
const prevFiltersRef = useRef({ type, category });
useEffect(() => {
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();
if (!bounds || bounds.length < 2) return;
const timer = setTimeout(async () => {
try {
const markers = await loadMarkers(bounds, type, category);
renderMarkersRef.current?.(Array.isArray(markers) ? markers : []);
} catch (e) {
// Фоновый запрос: молча оставляем прежние маркеры на месте.
}
}, BOUNDS_DEBOUNCE_MS);
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));
@@ -195,7 +463,7 @@ export default function MapView({ focusPostId, focusLat, focusLng, onPostClick,
return (
<div className="f-mapview">
{loading && (
<div className="f-mapview-status">
<div className="f-mapview-status" data-testid="mapview-loading">
<div className="f-spinner" />
</div>
)}
@@ -228,4 +496,4 @@ export default function MapView({ focusPostId, focusLat, focusLng, onPostClick,
)}
</div>
);
}
}

View File

@@ -0,0 +1,260 @@
/**
* Регрессия: первая загрузка маркеров должна уходить с границами карты.
*
* Раньше первый запрос висел на map.events.add('load'), которого у ymaps.Map
* в 2.1 нет — событие не наступало, fetch не уходил, а спиннер закрывал
* карту навсегда. Фейковый ymaps ниже намеренно НЕ умеет в 'load'.
*/
import { render, screen, waitFor, act } from "@testing-library/react";
import MapView from "./MapView";
// Реальный i18n, а не заглушка: MapView использует t() и без инициализации
// react-i18next сыплет предупреждение, а проверка текста ошибки теряла бы смысл.
import "../i18n";
jest.mock("../hooks/useGeolocation", () => ({
GEO_STATUS: {
IDLE: "idle",
LOADING: "loading",
SUCCESS: "success",
DENIED: "denied",
UNSUPPORTED: "unsupported",
TIMEOUT: "timeout",
},
// Геолокация в тестах не нужна и капризна (navigator.geolocation).
useGeolocation: () => ({ coords: null, status: "idle", requestLocation: jest.fn() }),
}));
const BOUNDS = [[55.7, 37.55], [55.8, 37.7]];
function installFakeYmaps({ boundsInitiallyNull = true } = {}) {
const listeners = {};
let bounds = boundsInitiallyNull ? null : BOUNDS;
const map = {
events: {
add(name, cb) {
(listeners[name] = listeners[name] || []).push(cb);
return { name, cb };
},
remove(sub) {
listeners[sub.name] = (listeners[sub.name] || []).filter((cb) => cb !== sub.cb);
},
},
geoObjects: { add() {}, removeAll() {} },
getBounds: () => bounds,
setCenter: jest.fn(),
destroy: jest.fn(),
};
window.ymaps = {
ready: (cb) => cb(),
Map: jest.fn(() => map),
GeoObjectCollection: jest.fn(function GeoObjectCollection() {
this.add = jest.fn();
this.removeAll = jest.fn();
}),
Placemark: jest.fn(function Placemark() {
this.events = { add() {} };
this.geometry = { setCoordinates() {} };
}),
templateLayoutFactory: { createClass: jest.fn(() => function Layout() {}) },
};
return {
map,
/** Имитирует первый расчёт вьюпорта — так ведёт себя настоящий API. */
publishBounds() {
bounds = BOUNDS;
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
panTo(next) {
bounds = next;
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
fireBoundsChangeOnly() {
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
};
}
let fetchMock;
beforeEach(() => {
jest.useFakeTimers();
fetchMock = jest.fn().mockResolvedValue({
ok: true,
json: async () => [
{ id: 1, latitude: 55.75, longitude: 37.61, type: "LOST", title: "Кошелёк" },
],
});
global.fetch = fetchMock;
});
afterEach(() => {
jest.useRealTimers();
delete window.ymaps;
jest.clearAllMocks();
});
function mapCall(index = 0) {
const url = fetchMock.mock.calls[index]?.[0] || "";
return new URL(url, "http://localhost");
}
test("первый запрос уходит с границами карты, а не пустым query", async () => {
const ymaps = installFakeYmaps();
render(<MapView focusPostId={null} focusLat={NaN} focusLng={NaN} onBack={() => {}} />);
// Границы появляются только после первого расчёта вьюпорта.
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.pathname).toBe("/api/v1/posts/map");
expect(url.searchParams.get("minLat")).toBe("55.7");
expect(url.searchParams.get("minLng")).toBe("37.55");
expect(url.searchParams.get("maxLat")).toBe("55.8");
expect(url.searchParams.get("maxLng")).toBe("37.7");
});
test("все четыре граничных параметра присутствуют в каждом запросе", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
for (const call of fetchMock.mock.calls) {
const url = new URL(call[0], "http://localhost");
for (const key of ["minLat", "maxLat", "minLng", "maxLng"]) {
expect(url.searchParams.get(key)).not.toBeNull();
}
}
});
test("опциональные фильтры type/category уезжают в том же запросе", async () => {
const ymaps = installFakeYmaps();
render(<MapView type="LOST" category="Электроника" onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.searchParams.get("type")).toBe("LOST");
expect(url.searchParams.get("category")).toBe("Электроника");
expect(url.searchParams.get("minLat")).toBe("55.7");
});
test("фильтры не добавляются, когда не заданы", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.searchParams.has("type")).toBe(false);
expect(url.searchParams.has("category")).toBe(false);
});
test("перемещение карты перезапрашивает маркеры один раз, несмотря на debounce", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
// Серия boundschange без пауз — должна схлопнуться в один запрос.
ymaps.fireBoundsChangeOnly();
ymaps.fireBoundsChangeOnly();
ymaps.fireBoundsChangeOnly();
expect(fetchMock).toHaveBeenCalledTimes(1);
await act(async () => {
jest.advanceTimersByTime(400);
});
// Новые границы = ровно один новый запрос.
ymaps.panTo([[55.9, 37.4], [56.0, 37.5]]);
await act(async () => {
jest.advanceTimersByTime(400);
});
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
const url = mapCall(1);
expect(url.searchParams.get("minLat")).toBe("55.9");
expect(url.searchParams.get("maxLng")).toBe("37.5");
});
test("одинаковые границы не порождают повторный запрос", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
ymaps.fireBoundsChangeOnly();
await act(async () => {
jest.advanceTimersByTime(400);
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
test("спиннер снимается и карта не остаётся закрыта оверлеем", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
await waitFor(() => {
expect(screen.queryByTestId("mapview-loading")).toBeNull();
});
expect(screen.queryByText("Ошибка загрузки карты")).toBeNull();
});
test("даже если границы так и не пришли, карта не висит в вечной загрузке", async () => {
installFakeYmaps();
render(<MapView onBack={() => {}} />);
await waitFor(
() => {
expect(screen.queryByTestId("mapview-loading")).toBeNull();
},
{ timeout: 8000 }
);
});
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}')`);
});

View File

@@ -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, onImageClick, 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, onImageClick, onLocat
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,21 +72,31 @@ export default function PostDetailModal({ postId, onClose, onImageClick, onLocat
</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}
onImageClick={onImageClick}
onLocationClick={onLocationClick}
onAuthRequired={onAuthRequired}
compact
/>
<>
<PostOnFeed
ad={post}
isOwner={isOwner}
onLocationClick={onLocationClick}
onAuthRequired={onAuthRequired}
compact={compact}
hideContact={hideContact}
/>
{footer?.(post)}
</>
)}
</div>
</div>

View File

@@ -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>
);
}

View File

@@ -12,22 +12,32 @@ 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,
onClose,
onNavClick,
onLogoClick,
isAuthenticated,
onLoginClick,
onRulesClick,
onReviewsClick,
onCreatePost,
onProfileClick,
onMapClick,
profileData,
}) {
const navigate = useNavigate();
@@ -41,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") {
@@ -80,7 +111,7 @@ export default function Sidebar({
type="button"
className="f-sb-logo-btn"
onClick={() => {
onLogoClick?.();
navigate("/");
onClose();
}}
title={t('nav.home')}
@@ -123,7 +154,7 @@ export default function Sidebar({
</button>
<button
type="button"
className="f-sb-item"
className={`f-sb-item${activeNav === "admin-campaigns" ? " active" : ""}`}
onClick={() => {
navigate("/admin/ads");
onClose();
@@ -131,6 +162,26 @@ export default function Sidebar({
>
{NavIcons.grid()} {t('adminPanel.campaignsNav')}
</button>
<button
type="button"
className={`f-sb-item${activeNav === "admin-posts" ? " active" : ""}`}
onClick={() => {
navigate("/admin/ads?tab=posts");
onClose();
}}
>
{NavIcons.rules()} {t('adminPanel.postsNav')}
</button>
<button
type="button"
className={`f-sb-item${activeNav === "admin-posts-rejected" ? " active" : ""}`}
onClick={() => {
navigate("/admin/ads?tab=rejected");
onClose();
}}
>
{NavIcons.rules()} {t('adminPanel.postsRejectedNav')}
</button>
</>
)}
</nav>
@@ -162,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" />
@@ -198,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();
}}
/>
)}
</>
);
}

22
src/components/Toast.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
/**
* Типы для Toast.
*
* Почему отдельный .d.ts, а не JSDoc в Toast.jsx: у функции с деструктурированным
* параметром TS сворачивает тип в `string` (JSDoc-теги применяются к самому
* объекту параметра, а не к его полям). Из-за этого любой .tsx-файл, рендерящий
* <Toast .../>, падал с TS2322. Объявление отделяет контракт от реализации.
*/
type ToastType = "error" | "success";
interface ToastProps {
/** Текст сообщения. Пустая строка/null — тост не рендерится. */
message: string | null | undefined;
type?: ToastType;
/** Вызывается по истечении duration и по клику на крестик. */
onDismiss?: () => void;
duration?: number;
}
declare function Toast(props: ToastProps): JSX.Element | null;
export default Toast;

View File

@@ -1,5 +1,5 @@
// src/components/Toast.jsx
import { useEffect } from "react";
import { useEffect, useRef } from "react";
/**
* Toast — всплывающее сообщение об ошибке/успехе, автоматически скрывается.
@@ -10,10 +10,16 @@ import { useEffect } from "react";
* @param {number} [duration=4000] — время жизни в мс
*/
export default function Toast({ message, type = "error", onDismiss, duration = 4000 }) {
// onDismiss почти всегда — свежий инлайн-стрелки. Если держать его в
// зависимостях useEffect, любой ре-рендер родителя (сообщения чата, поллинг
// рекламы) перезапускал бы отсчёт и тост висел бы бесконечно.
const dismissRef = useRef(onDismiss);
dismissRef.current = onDismiss;
useEffect(() => {
const timer = setTimeout(onDismiss, duration);
const timer = setTimeout(() => dismissRef.current?.(), duration);
return () => clearTimeout(timer);
}, [onDismiss, duration]);
}, [duration]);
if (!message) return null;

View File

@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { toSafeHttpUrl } from "../utils/safeUrl";
import { useTranslation } from "react-i18next";
import CloseIcon from "./icons/CloseIcon";
import {
@@ -106,14 +107,15 @@ export default function UploadAdModal({ onClose }) {
if (creating) return;
let targetUrl = newTargetUrl.trim();
if (targetUrl) {
if (!/^https?:\/\//i.test(targetUrl)) targetUrl = `https://${targetUrl}`;
try {
// eslint-disable-next-line no-new
new URL(targetUrl);
} catch {
if (!/^[a-z][a-z0-9+.-]*:/i.test(targetUrl)) targetUrl = `https://${targetUrl}`;
// Бэкенд принимает только абсолютный http(s) — проверяем так же,
// иначе "javascript:..." дошёл бы до сервера и вернулся бы 400
const safe = toSafeHttpUrl(targetUrl);
if (!safe) {
setCreateError(t("adminPanel.urlInvalid"));
return;
}
targetUrl = safe;
}
setCreating(true);
setCreateError("");

View File

@@ -3,6 +3,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { isSafeHttpUrl } from "../../utils/safeUrl";
import CloseIcon from "../icons/CloseIcon";
import {
createAdvertising,
@@ -37,6 +38,9 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
const [progress, setProgress] = useState(null); // 0..100 во время PUT в MinIO
const [stepError, setStepError] = useState(""); // ошибка конкретного шага
const [submitError, setSubmitError] = useState(""); // общая ошибка
// Объявление, уже созданное на бэкенде, если упала загрузка видео: повторная
// отправка продолжает с presign, а не создаёт второе объявление-сироту
const createdAdRef = useRef(null);
// IMAGE-загрузка: файл, превью (object URL) и mediaKey, полученный с бэкенда.
const [mediaKey, setMediaKey] = useState("");
@@ -55,7 +59,9 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
const schema = useMemo(
() => z.object({
type: z.enum(["IMAGE", "VIDEO"]),
targetUrl: z.string().trim().url(t("adminPanel.urlInvalid")),
// Бэкенд принимает только абсолютный http(s) (иначе 400): z.url()
// пропустил бы и "javascript:", и "ftp:"
targetUrl: z.string().trim().refine(isSafeHttpUrl, t("adminPanel.urlInvalid")),
weight: z.coerce.number().int(t("adminPanel.weightInvalid")).positive(t("adminPanel.weightInvalid")),
}),
[t]
@@ -169,14 +175,18 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
}
try {
// Шаг 1 (общий): создание объявления
const ad = await createAdvertising({
// Шаг 1 (общий): создание объявления. Для VIDEO после сбоя загрузки
// берём уже созданное (тип и кампания те же, правки URL/веса — через
// редактирование в списке).
const reuse = adType === "VIDEO" && createdAdRef.current?.type === "VIDEO";
const ad = reuse ? createdAdRef.current : await createAdvertising({
campaignId,
type: adType,
mediaKey: adType === "IMAGE" ? mediaKey : null,
targetUrl,
weight: Number(weight),
});
if (adType === "VIDEO") createdAdRef.current = ad;
if (adType === "IMAGE") {
// IMAGE → transcodingStatus сразу "READY", загрузки нет.
@@ -195,12 +205,15 @@ export default function AdvertisingCreateModal({ campaignId, onClose, onCreated
);
// Модалку закрываем сразу после confirm; транскодинг поллится страницей.
createdAdRef.current = null;
onCreated({ ...ad, transcodingStatus: "PENDING" });
} catch (err) {
setSubmitting(false);
setProgress(null);
if (err?.status === 400) {
setSubmitError(t("adminPanel.adCreateFailed"));
// Текст бэкенда объясняет причину (ссылка не http(s), вес, ключ
// confirm-upload не из presign этого объявления)
setSubmitError(err.serverMessage || t("adminPanel.adCreateFailed"));
return;
}
// Контекст не теряем: по шагу показываем понятную ошибку

View File

@@ -3,6 +3,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { isSafeHttpUrl } from "../../utils/safeUrl";
import CloseIcon from "../icons/CloseIcon";
import { updateAdvertising } from "../../api/adminAdsApi";
@@ -18,7 +19,9 @@ export default function AdvertisingEditModal({ ad, onClose, onUpdated }) {
const schema = useMemo(
() => z.object({
targetUrl: z.string().trim().url(t("adminPanel.urlInvalid")),
// Бэкенд принимает только абсолютный http(s) (иначе 400): z.url()
// пропустил бы и "javascript:", и "ftp:"
targetUrl: z.string().trim().refine(isSafeHttpUrl, t("adminPanel.urlInvalid")),
weight: z.coerce.number().int(t("adminPanel.weightInvalid")).positive(t("adminPanel.weightInvalid")),
}),
[t]

View File

@@ -0,0 +1,152 @@
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getCampaignStats } from "../../api/adminAdsApi";
const DEFAULT_DAYS = 30;
const MAX_DAYS = 366;
/** Дата в формате YYYY-MM-DD по локальному календарю (не UTC). */
export function toIsoDate(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
const d = String(date.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
}
/** Последние 30 дней включая сегодня — тот же период, что бэкенд берёт по умолчанию. */
export function defaultStatsRange(now = new Date()) {
const from = new Date(now);
from.setDate(from.getDate() - (DEFAULT_DAYS - 1));
return { from: toIsoDate(from), to: toIsoDate(now) };
}
/** Число дней from..to включительно, или null для некорректного диапазона. */
export function rangeDays(from, to) {
const start = Date.parse(`${from}T00:00:00Z`);
const end = Date.parse(`${to}T00:00:00Z`);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return null;
return Math.round((end - start) / 86400000) + 1;
}
function formatCtr(value) {
return typeof value === "number" ? `${value.toFixed(2)}%` : "—";
}
/**
* Статистика кампании: показы, клики и CTR — итог и по каждому объявлению
* (GET /api/v1/admin/campaigns/{id}/stats). Показ засчитывается по факту
* видимости баннера (см. useAdViewability), а не по выдаче.
*
* @param {{ campaignId: number, ads?: Array<{id, type, targetUrl}> }} props
*/
export default function CampaignStatsPanel({ campaignId, ads = [] }) {
const { t, i18n } = useTranslation();
const [range, setRange] = useState(() => defaultStatsRange());
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const days = rangeDays(range.from, range.to);
const rangeError = days === null
? t("adminPanel.statsRangeInvalid")
: days > MAX_DAYS ? t("adminPanel.statsRangeTooLong", { max: MAX_DAYS }) : "";
const load = useCallback(async (signal) => {
setLoading(true);
setError("");
try {
const data = await getCampaignStats(campaignId, range);
if (signal.cancelled) return;
setStats(data);
} catch (err) {
if (signal.cancelled) return;
setStats(null);
// 404 — бэкенд ещё без эндпоинта статистики
setError(err?.status === 404 ? t("adminPanel.statsUnavailable") : t("adminPanel.statsLoadError"));
} finally {
if (!signal.cancelled) setLoading(false);
}
}, [campaignId, range, t]);
useEffect(() => {
if (rangeError) return undefined;
const signal = { cancelled: false };
load(signal);
return () => { signal.cancelled = true; };
}, [load, rangeError]);
const number = (value) => (typeof value === "number" ? value.toLocaleString(i18n.language) : "—");
const adById = new Map(ads.map((ad) => [ad.id, ad]));
return (
<div className="admp-stats">
<div className="admp-stats-range">
<label>
{t("adminPanel.statsFrom")}
<input
type="date"
className="f-m-field"
value={range.from}
max={range.to}
onChange={(e) => setRange((r) => ({ ...r, from: e.target.value }))}
/>
</label>
<label>
{t("adminPanel.statsTo")}
<input
type="date"
className="f-m-field"
value={range.to}
min={range.from}
onChange={(e) => setRange((r) => ({ ...r, to: e.target.value }))}
/>
</label>
</div>
{rangeError && <div className="f-err-msg">{rangeError}</div>}
{!rangeError && loading && <div className="admp-no-ads">{t("adminPanel.statsLoading")}</div>}
{!rangeError && !loading && error && <div className="f-err-msg admp-load-error">{error}</div>}
{!rangeError && !loading && !error && stats && (
<>
<div className="admp-stats-totals">
<div><span>{t("adminPanel.statsImpressions")}</span><strong>{number(stats.impressions)}</strong></div>
<div><span>{t("adminPanel.statsClicks")}</span><strong>{number(stats.clicks)}</strong></div>
<div><span>CTR</span><strong>{formatCtr(stats.ctr)}</strong></div>
</div>
{Array.isArray(stats.advertisings) && stats.advertisings.length > 0 ? (
<table className="admp-stats-table">
<thead>
<tr>
<th scope="col">{t("adminPanel.statsAd")}</th>
<th scope="col">{t("adminPanel.statsImpressions")}</th>
<th scope="col">{t("adminPanel.statsClicks")}</th>
<th scope="col">CTR</th>
</tr>
</thead>
<tbody>
{stats.advertisings.map((row) => {
const ad = adById.get(row.advertisingId);
return (
<tr key={row.advertisingId}>
<td className="admp-stats-ad" title={ad?.targetUrl}>
#{row.advertisingId}
{ad && <span> · {ad.type} · {ad.targetUrl}</span>}
</td>
<td>{number(row.impressions)}</td>
<td>{number(row.clicks)}</td>
<td>{formatCtr(row.ctr)}</td>
</tr>
);
})}
</tbody>
</table>
) : (
<div className="admp-no-ads">{t("adminPanel.statsEmpty")}</div>
)}
</>
)}
</div>
);
}

View File

@@ -0,0 +1,260 @@
// src/components/admin/PostsTab.jsx
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import PostOnFeed from "../../pages/PostOnFeed";
import CreateUpdatePost from "../../pages/CreateUpdatePost";
import Toast from "../Toast";
import {
getAdminPosts,
getAdminRejectedPosts,
deleteAdminPost,
updateAdminPostStatus,
} from "../../api/adminContentApi";
const PAGE_SIZE = 20;
const SEARCH_DEBOUNCE_MS = 400;
const TYPE_FILTERS = [
{ value: "", labelKey: "adminPanel.filterTypeAll" },
{ value: "LOSS", labelKey: "postCard.loss" },
{ value: "FOUND", labelKey: "postCard.found" },
];
const STATUS_FILTERS = [
{ value: "", labelKey: "adminPanel.filterStatusAll" },
{ value: "ACTIVE", labelKey: "adminPanel.statusActive" },
{ value: "CLOSED", labelKey: "adminPanel.statusClosed" },
];
/** Подпись автора объявления: у бэкенда поле называется по-разному в разных DTO. */
function authorLabelOf(post) {
const name = post.ownerName || post.authorName || post.userName ||
[post.ownerFirstName, post.ownerLastName].filter(Boolean).join(" ");
const login = post.ownerLogin || post.authorLogin || post.userLogin;
const parts = [name, login ? `@${login}` : null].filter(Boolean);
return parts.length ? parts.join(" · ") : null;
}
/**
* Вкладка «Все объявления» админ-панели.
*
* Показывает ВСЕ объявления площадки с тем же набором действий, что и вкладка
* «Мои объявления» у обычного пользователя (редактирование, удаление, отметка
* «найдено»), плюс возможность вернуть закрытое объявление обратно в ленту.
*
* Все мутации идут через /api/v1/admin/posts — сервер проверяет роль ADMIN
* независимо от того, что интерфейс вообще показал админские кнопки.
*
* Разметка рассчитана на то, что страница уже нарисовала .admp > .admp-inner,
* поэтому собственного скролл-контейнера у вкладки нет.
*/
export default function PostsTab({ isAdmin, mode = "all" }) {
const { t } = useTranslation();
const isRejectedMode = mode === "rejected";
const [posts, setPosts] = useState([]);
const [page, setPage] = useState(0);
const [hasMore, setHasMore] = useState(true);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState("");
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
const [typeFilter, setTypeFilter] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [editing, setEditing] = useState(null);
const [busyId, setBusyId] = useState(null);
const [toast, setToast] = useState(null);
const showToast = useCallback((message, type = "success") => {
setToast({ message, type });
}, []);
// Дебаунс поиска, чтобы не дёргать сервер на каждое нажатие клавиши
useEffect(() => {
const timer = setTimeout(() => setSearch(searchInput.trim()), SEARCH_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [searchInput]);
// Смена фильтра сбрасывает пагинацию, поэтому load всегда стартует с 0-й страницы.
const load = useCallback(async ({ pageNum = 0, append = false, silent = false } = {}) => {
if (!isAdmin) return;
if (append) setLoadingMore(true);
else if (!silent) setLoading(true);
setError("");
try {
const fetcher = isRejectedMode ? getAdminRejectedPosts : getAdminPosts;
const result = await fetcher({ page: pageNum, size: PAGE_SIZE, search, type: typeFilter, status: statusFilter });
setPosts((prev) => (append ? [...prev, ...result.items] : result.items));
setHasMore(!result.last);
setPage(pageNum);
} catch {
setError(t("adminPanel.postsLoadError"));
if (!append) setPosts([]);
setHasMore(false);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, [isAdmin, search, typeFilter, statusFilter, t, isRejectedMode]);
// Первичная загрузка + перезагрузка при смене фильтров
useEffect(() => {
load({ pageNum: 0 });
}, [load]);
const patchPost = useCallback((postId, patch) => {
setPosts((prev) => prev.map((p) => (p.id === postId ? { ...p, ...patch } : p)));
}, []);
const handleDelete = useCallback(async (postId) => {
if (!window.confirm(t("adminPanel.postsConfirmDelete"))) return;
setBusyId(postId);
try {
await deleteAdminPost(postId);
setPosts((prev) => prev.filter((p) => p.id !== postId));
showToast(t("adminPanel.postsDeleted"));
} catch {
showToast(t("adminPanel.postsDeleteFailed"), "error");
} finally {
setBusyId(null);
}
}, [t, showToast]);
const setStatus = useCallback(async (postId, status) => {
const isClose = status === "CLOSED";
if (!window.confirm(isClose ? t("adminPanel.postsConfirmClose") : t("adminPanel.postsConfirmReopen"))) return;
setBusyId(postId);
try {
const updated = await updateAdminPostStatus(postId, status);
// Сервер может вернуть неполный DTO — мержим, чтобы не потерять поля карточки.
patchPost(postId, { ...(updated || {}), id: postId, status });
showToast(isClose ? t("adminPanel.postsClosed") : t("adminPanel.postsReopened"));
} catch {
showToast(t("adminPanel.postsStatusFailed"), "error");
} finally {
setBusyId(null);
}
}, [t, showToast, patchPost]);
const handleEditSaved = useCallback(() => {
// Перезагружаем текущую страницу: сервер мог изменить статус или дату.
load({ pageNum: page, silent: true });
showToast(t("adminPanel.postsUpdated"));
}, [load, page, showToast, t]);
const contentStyle = useMemo(() => ({ opacity: busyId === null ? 1 : 0.75 }), [busyId]);
if (!isAdmin) return null;
return (
<>
<div className="admp-toolbar admp-toolbar--filters">
<input
type="search"
className="f-m-field admp-search"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={t("adminPanel.postsSearchPlaceholder")}
aria-label={t("adminPanel.postsSearchPlaceholder")}
/>
<div className="admp-filter-group" role="group" aria-label={t("adminPanel.postsTypeFilter")}>
{TYPE_FILTERS.map(({ value, labelKey }) => (
<button
key={value || "all"}
type="button"
className={`admp-chip${typeFilter === value ? " active" : ""}`}
onClick={() => setTypeFilter(value)}
>
{t(labelKey)}
</button>
))}
</div>
<div className="admp-filter-group" role="group" aria-label={t("adminPanel.postsStatusFilter")}>
{STATUS_FILTERS.map(({ value, labelKey }) => (
<button
key={value || "all"}
type="button"
className={`admp-chip${statusFilter === value ? " active" : ""}`}
onClick={() => setStatusFilter(value)}
>
{t(labelKey)}
</button>
))}
</div>
<button
type="button"
className="admp-btn admp-btn--ghost"
onClick={() => load({ pageNum: 0 })}
disabled={loading}
>
{t("adminPanel.refresh")}
</button>
</div>
<div className="admp-session-hint">
{loading
? t("adminPanel.postsLoading")
: t("adminPanel.postsHint", { count: posts.length })}
</div>
{error && <div className="f-err-msg admp-load-error">{error}</div>}
{loading && (
<div className="f-center admp-empty">
<div className="f-spinner" />
</div>
)}
{!loading && posts.length === 0 && (
<div className="f-center admp-empty">
<div className="f-center-icon">📋</div>
<div className="f-center-title">{t("adminPanel.postsEmpty")}</div>
<div className="f-center-sub">{t("adminPanel.postsEmptySub")}</div>
</div>
)}
<div className="admp-posts-grid" style={contentStyle}>
{posts.map((post) => (
<PostOnFeed
key={post.id}
ad={post}
isOwner
allowEditClosed
authorLabel={authorLabelOf(post)}
onEdit={setEditing}
onDelete={handleDelete}
onMarkFound={(id) => setStatus(id, "CLOSED")}
onReopen={(id) => setStatus(id, "ACTIVE")}
/>
))}
</div>
{!loading && hasMore && (
<div className="admp-more">
<button
type="button"
className="admp-btn admp-btn--ghost"
disabled={loadingMore}
onClick={() => load({ pageNum: page + 1, append: true })}
>
{loadingMore ? t("adminPanel.postsLoading") : t("adminPanel.loadMore")}
</button>
</div>
)}
{editing && (
<CreateUpdatePost
adminMode
initialData={editing}
onClose={() => setEditing(null)}
onSuccess={handleEditSaved}
/>
)}
{toast && <Toast message={toast.message} type={toast.type} onDismiss={() => setToast(null)} />}
</>
);
}

View 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);
});

View File

@@ -1,20 +1,45 @@
export default function ChatHeader({ title, onBack, avatar, statusLabel, statusConnected }) {
/**
* Шапка чата. С 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>
)}
<div className="chat-header-title">{title}</div>
{statusLabel !== undefined ? (
<div className={`chat-status${statusConnected ? " connected" : ""}`}>
{statusLabel}
</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>
);
}
}

View File

@@ -1,58 +1,130 @@
import { useRef } from "react";
import Picker from "@emoji-mart/react";
import emojiData from "@emoji-mart/data";
import { useClickOutside } from "../../hooks/useClickOutside";
import { useTheme } from "../../context/ThemeContext";
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,
onEmojiSelect,
showEmoji,
onToggleEmoji,
onCloseEmoji,
connected,
placeholder,
attach,
sending = false,
notice = null,
locked = false,
}) {
const emojiPickerRef = useRef(null);
useClickOutside(emojiPickerRef, onCloseEmoji, showEmoji);
const { theme } = useTheme();
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">
{showEmoji && (
<div className="chat-emoji-picker" ref={emojiPickerRef}>
<Picker
data={emojiData}
onEmojiSelect={onEmojiSelect}
theme={theme}
previewPosition="none"
skinTonePosition="none"
searchPosition="sticky"
maxSearchResults={30}
perLine={8}
/>
<div 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="button"
className={`chat-emoji-btn${showEmoji ? " active" : ""}`}
onClick={onToggleEmoji}
>
😊
</button>
<button type="submit" className="chat-send-btn" disabled={!connected}>
<button type="submit" className="chat-send-btn" disabled={!canSend} aria-busy={sending}>
➤
</button>
</form>
)}
</div>
);
}
}

View File

@@ -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>

View 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>
);
}

View 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("привет");
});

View 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);
});

View 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>
);
}

View 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>
);
}

View 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("");
});

View 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>
);
}

View File

@@ -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>
);

View 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>
);
}

View File

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

View File

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

View File

@@ -0,0 +1,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>
),
};

View File

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

View File

@@ -0,0 +1,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();
}}
/>
)}
</>
);
}

View File

@@ -0,0 +1,59 @@
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import CitySheet from "./CitySheet";
/**
* CityQuickFilter — мобильный фильтр городов: круглая кнопка со счётчиком
* рядом с поиском + строка чипов выбранных городов + нижняя шторка выбора.
*
* Возвращает фрагмент: кнопка и строка чипов — соседние элементы флекс-панели
* .f-search-panel (чипы переносятся на свою строку через flex-basis: 100%).
* Видимость (только телефон) управляется CSS.
*/
export default function CityQuickFilter({ cities, value, onChange }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const close = useCallback(() => setOpen(false), []);
return (
<>
<button
type="button"
className={`f-city-btn${value.length ? " active" : ""}`}
onClick={() => setOpen(true)}
aria-label={String(t("feed.filterCitiesOpen"))}
aria-haspopup="dialog"
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
strokeLinecap="round" strokeLinejoin="round" width="20" height="20">
<circle cx="12" cy="10" r="3" />
<path d="M12 21s-7-5.6-7-11a7 7 0 0 1 14 0c0 5.4-7 11-7 11z" />
</svg>
{value.length > 0 && <span className="f-city-btn-badge">{value.length}</span>}
</button>
{value.length > 0 && (
<div className="f-city-chips">
{value.map(city => (
<span key={city} className="f-city-chip">
{city}
<button
type="button"
className="f-city-chip-remove"
aria-label={String(t("feed.filterCitiesRemove"))}
onClick={() => onChange(value.filter(c => c !== city))}
>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2.5" strokeLinecap="round" width="12" height="12">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</span>
))}
</div>
)}
<CitySheet open={open} onClose={close} cities={cities} value={value} onChange={onChange} />
</>
);
}

View File

@@ -0,0 +1,174 @@
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence, useDragControls } from "framer-motion";
import { useTranslation } from "react-i18next";
import { useCityOptions } from "../../hooks/useCityOptions";
// Сколько нужно протянуть шторку вниз (px) или с какой скоростью, чтобы она закрылась
const DRAG_CLOSE_OFFSET = 100;
const DRAG_CLOSE_VELOCITY = 500;
/**
* CitySheet — мобильная нижняя шторка выбора городов.
*
* Работает с черновиком: выбор применяется только по «Показать»,
* закрытие свайпом/тапом по фону изменения отбрасывает.
*
* @param {boolean} open
* @param {() => void} onClose
* @param {string[]} cities — доступные города (из /posts/cities)
* @param {string[]} value — применённые города
* @param {(next: string[]) => void} onChange — применить выбор
*/
export default function CitySheet({ open, onClose, cities, value, onChange }) {
const { t } = useTranslation();
const [draft, setDraft] = useState(value);
const [query, setQuery] = useState("");
// Тянуть шторку можно только за ручку/заголовок — иначе drag мешает скроллу списка
const dragControls = useDragControls();
// При каждом открытии черновик начинается с применённого выбора
useEffect(() => {
if (open) {
setDraft(value);
setQuery("");
}
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!open) return;
const onKeyDown = (e) => e.key === "Escape" && onClose();
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [open, onClose]);
const { options, typedCity } = useCityOptions(cities, draft, query);
// Города, добавленные свободным вводом, в общем списке отсутствуют — показываем их сверху
const q = query.trim().toLowerCase();
const customSelected = draft.filter(c =>
!cities.includes(c) && (!q || c.toLowerCase().includes(q)));
const rows = [...customSelected, ...options];
const toggle = (city) => {
setDraft(d => d.includes(city) ? d.filter(c => c !== city) : [...d, city]);
};
// Введённый город, которого нет в списке, тоже применяется: лента покажет
// «В этом городе нет объявлений»
const apply = () => {
onChange(typedCity ? [...draft, typedCity] : draft);
onClose();
};
return createPortal(
<AnimatePresence>
{open && (
<>
<motion.div
key="backdrop"
className="f-sheet-backdrop"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={onClose}
/>
<motion.div
key="sheet"
className="f-sheet"
role="dialog"
aria-modal="true"
aria-label={String(t("feed.filterCitiesTitle"))}
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 32, stiffness: 320 }}
drag="y"
dragConstraints={{ top: 0, bottom: 0 }}
dragElastic={{ top: 0, bottom: 0.6 }}
dragListener={false}
dragControls={dragControls}
onDragEnd={(_, info) => {
if (info.offset.y > DRAG_CLOSE_OFFSET || info.velocity.y > DRAG_CLOSE_VELOCITY) {
onClose();
}
}}
>
<div className="f-sheet-grab" onPointerDown={e => dragControls.start(e)}>
<div className="f-sheet-handle" aria-hidden="true" />
<div className="f-sheet-header">
<h3 className="f-sheet-title">{t("feed.filterCitiesTitle")}</h3>
{draft.length > 0 && (
<span className="f-sheet-count">{draft.length}</span>
)}
</div>
</div>
<div className="f-sheet-search">
<svg className="f-search-icon" viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.35-4.35" />
</svg>
<input
className="f-sheet-search-input"
type="text"
value={query}
placeholder={t("feed.filterCitiesSearch")}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => {
if (e.key === "Enter") {
e.preventDefault();
apply();
}
}}
autoComplete="off"
enterKeyHint="search"
/>
</div>
<div className="f-sheet-list">
{rows.length === 0 && (
<div className="f-sheet-empty">{t("feed.filterCitiesEmpty")}</div>
)}
{rows.map(city => {
const selected = draft.includes(city);
return (
<button key={city} type="button"
className={`f-sheet-row${selected ? " selected" : ""}`}
aria-pressed={selected}
onClick={() => toggle(city)}>
<span className="f-sheet-check">
{selected && (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"
width="12" height="12">
<path d="M20 6 9 17l-5-5" />
</svg>
)}
</span>
<span className="f-sheet-row-label">{city}</span>
</button>
);
})}
</div>
<div className="f-sheet-actions">
<button type="button" className="f-sheet-btn"
onClick={() => setDraft([])}>
{t("feed.filterCitiesReset")}
</button>
<button type="button" className="f-sheet-btn f-sheet-btn-primary" onClick={apply}>
{t("feed.filterCitiesApply")}
</button>
</div>
</motion.div>
</>
)}
</AnimatePresence>,
document.body
);
}

View File

@@ -1,28 +0,0 @@
import { useEffect, useState } from "react";
/**
* Отдельный блюр-слой поверх ленты, независим от FeedTopBar.
* Прижат к верху общего контейнера, высота подстраивается под
* реальную высоту topBar (включая safe-area на iOS).
*/
export default function FeedBlurMask({ topBarRef }) {
const [height, setHeight] = useState(56);
useEffect(() => {
const el = topBarRef?.current;
if (!el) return;
const update = () => setHeight(el.getBoundingClientRect().height || 56);
update();
const ro = new ResizeObserver(update);
ro.observe(el);
return () => ro.disconnect();
}, [topBarRef]);
return (
<div
className="f-feed-blur-mask"
style={{ height }}
aria-hidden="true"
/>
);
}

View File

@@ -7,7 +7,6 @@ const AD_EVERY = 10;
export default function FeedContent({
loading,
cityLoading,
citySearchActive,
error,
filteredAds,
@@ -16,7 +15,7 @@ export default function FeedContent({
onEdit,
onDelete,
onMarkFound,
onImageClick,
onReopen,
onLocationClick,
onAuthRequired,
showAds = false,
@@ -29,7 +28,7 @@ export default function FeedContent({
() => withAds(filteredAds, showAds ? AD_EVERY : 0),
[filteredAds, showAds]
);
if (loading || (citySearchActive && cityLoading)) {
if (loading) {
return (
<div className="f-center">
<div className="f-spinner-wrap">
@@ -88,8 +87,8 @@ export default function FeedContent({
onEdit={activeNav === "myads" ? onEdit : undefined}
onDelete={activeNav === "myads" ? onDelete : undefined}
onMarkFound={activeNav === "myads" ? onMarkFound : undefined}
onReopen={activeNav === "myads" ? onReopen : undefined}
isOwner={activeNav === "myads"}
onImageClick={onImageClick}
onLocationClick={onLocationClick}
onAuthRequired={onAuthRequired}
/>

View File

@@ -1,4 +1,64 @@
import { useEffect, useRef, useState } from "react";
import { getSearchSuggestions } from "../../api/searchApi";
const SUGGEST_DELAY_MS = 150;
/** Заменяет последнее (недописанное) слово строки на подсказку. */
function applySuggestion(value, word) {
return value.replace(/[\p{L}\p{N}]+$/u, "") + word + " ";
}
export default function FeedSearchBar({ value, onChange, t }) {
const [suggestions, setSuggestions] = useState([]);
const [active, setActive] = useState(-1);
const [focused, setFocused] = useState(false);
const inputRef = useRef(null);
// Подсказки нужны, только пока строка заканчивается буквой/цифрой (слово дописывается)
useEffect(() => {
if (!focused || !/[\p{L}\p{N}]$/u.test(value)) {
setSuggestions([]);
return;
}
const controller = new AbortController();
const timer = setTimeout(() => {
getSearchSuggestions(value, controller.signal)
.then(words => {
setSuggestions(Array.isArray(words) ? words : []);
setActive(-1);
})
.catch(() => {}); // подсказки необязательны — без них поиск работает как раньше
}, SUGGEST_DELAY_MS);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [value, focused]);
const open = focused && suggestions.length > 0;
const pick = word => {
onChange(applySuggestion(value, word));
setSuggestions([]);
inputRef.current?.focus();
};
const onKeyDown = e => {
if (!open) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActive(i => (i + 1) % suggestions.length);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive(i => (i <= 0 ? suggestions.length - 1 : i - 1));
} else if (e.key === "Enter" && active >= 0) {
e.preventDefault();
pick(suggestions[active]);
} else if (e.key === "Escape") {
setSuggestions([]);
}
};
return (
<div className="f-search-bar">
<svg className="f-search-icon" viewBox="0 0 24 24" fill="none"
@@ -7,11 +67,21 @@ export default function FeedSearchBar({ value, onChange, t }) {
<path d="m21 21-4.35-4.35" />
</svg>
<input
ref={inputRef}
className="f-search-input"
type="text"
placeholder={t('feed.searchPlaceholder')}
value={value}
onChange={e => onChange(e.target.value)}
onKeyDown={onKeyDown}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
role="combobox"
aria-expanded={open}
aria-controls="f-search-suggest"
aria-autocomplete="list"
aria-activedescendant={open && active >= 0 ? `f-search-suggest-${active}` : undefined}
autoComplete="off"
/>
{value && (
<button className="f-search-clear" onClick={() => onChange("")}>
@@ -21,6 +91,27 @@ export default function FeedSearchBar({ value, onChange, t }) {
</svg>
</button>
)}
{open && (
<ul className="f-search-suggest" id="f-search-suggest" role="listbox">
{suggestions.map((word, i) => (
<li
key={word}
id={`f-search-suggest-${i}`}
role="option"
aria-selected={i === active}
className={`f-search-suggest-item${i === active ? " is-active" : ""}`}
// mousedown, а не click: иначе blur инпута закроет список раньше выбора
onMouseDown={e => {
e.preventDefault();
pick(word);
}}
onMouseEnter={() => setActive(i)}
>
{word}
</li>
))}
</ul>
)}
</div>
);
}
}

View File

@@ -35,6 +35,9 @@ export default function PullToRefresh({ containerRef, onRefresh, disabled = fals
const el = containerRef.current;
if (!el) return;
el.classList.toggle("f-ptr-active", visible);
// Размонтирование с visible=true иначе навсегда оставило бы маску
// затухания и блокировку pointer-events на контейнере ленты.
return () => el.classList.remove("f-ptr-active");
}, [visible, containerRef]);
useEffect(() => {

View File

@@ -1,21 +0,0 @@
export default function TypeFilterBar({ value, onChange, t }) {
const options = [
{ key: "loss", label: t('feed.filterLoss') },
{ key: null, label: t('feed.filterAll') },
{ key: "found", label: t('feed.filterFound') },
];
return (
<div className="f-filter-bar">
{options.map(opt => (
<button
key={opt.key ?? "all"}
className={`f-filter-btn${value === opt.key ? " active" : ""}`}
onClick={() => onChange(opt.key)}
>
{opt.label}
</button>
))}
</div>
);
}

View File

@@ -0,0 +1,8 @@
export default function CheckIcon ({ size = 12 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<polyline points="20 6 9 17 4 12" />
</svg>
);
}

View File

@@ -1,10 +0,0 @@
export default function HeartIcon({filled}) {
return (
<svg width={14} height={14} viewBox="0 0 24 24"
fill={filled ? "#ff6b6b" : "none"} stroke="#ff6b6b" strokeWidth={2}
strokeLinecap="round">
<path
d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
</svg>
);
}

View File

@@ -1,13 +0,0 @@
import magnifier from "../../assets/magnifier.png";
export default function LogoIcon() {
return (
<img
src={magnifier}
alt="logo"
width={20}
height={20}
style={{ objectFit: "contain" }}
/>
);
}

View File

@@ -1,10 +0,0 @@
export default function MapIcon() {
return (
<svg width={14} height={14} viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth={2} strokeLinecap="round">
<polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/>
<line x1="8" y1="2" x2="8" y2="18"/>
<line x1="16" y1="6" x2="16" y2="22"/>
</svg>
);
}

View File

@@ -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" />

View File

@@ -19,7 +19,9 @@ export default function AppTopBar({
}) {
const { t } = useTranslation();
return (
<div className="f-topbar">
// Без названия сервиса — заголовок строго по центру экрана (см. .f-topbar-centered),
// иначе он центрировался бы между кнопками разной ширины и уезжал влево
<div className={`f-topbar${hideWordmark ? " f-topbar-centered" : ""}`}>
<button className="f-menu-btn" onClick={onMenuClick}>
<MenuIcon />
</button>

View File

@@ -1,6 +1,6 @@
import { useTranslation } from 'react-i18next';
import CloseIcon from "../icons/CloseIcon";
import { MAX_SIZE_MB as MAX_PHOTO_SIZE_MB } from "../../hooks/useImageUpload";
import { MAX_SOURCE_SIZE_MB as MAX_PHOTO_SIZE_MB } from "../../hooks/useImageUpload";
// ─── Input field component ───────────────────────────────────────────────────
function InputField({ label, error, ...props }) {
@@ -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)}
/>
);
}

View File

@@ -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

View 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();
});

View File

@@ -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');
}

View File

@@ -3,8 +3,16 @@ export const API_URL = process.env.REACT_APP_API_URL || "http://localhost:8080";
export function getImageUrl(filename) {
if (!filename) return null;
if (filename.startsWith("http")) return filename;
if (filename.startsWith("/")) return `${API_URL}${filename}`;
return `${API_URL}/api/v1/files/${filename}`;
if (filename.startsWith("/")) return `${API_URL}${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 (ошибки отправки сообщений чата: пустое или
* длинное сообщение, нет доступа). Бэкенд до ветки backend-review отклоняет
* эту подписку и закрывает STOMP-соединение, поэтому включается флагом
* REACT_APP_WS_ERROR_QUEUE=true после деплоя нового бэкенда.
*/
export const WS_ERROR_QUEUE_ENABLED = process.env.REACT_APP_WS_ERROR_QUEUE === "true";

View File

@@ -1,9 +1,9 @@
export const NAV_ITEMS = [
{ icon: "grid", key: "home", labelKey: "nav.home" },
{ icon: "chat", key: "chat", labelKey: "nav.chat" },
{ icon: "box", key: "items", labelKey: "nav.items" },
{ icon: "paw", key: "pets", labelKey: "nav.pets" },
{ icon: "file", key: "myads", labelKey: "nav.myAds" },
{ icon: "chat", key: "chat", labelKey: "nav.chat" },
{ icon: "plus", key: "create", labelKey: "nav.create" },
];
@@ -12,10 +12,24 @@ export const NAV_BOTTOM = [
{ icon: "rules", key: "rules", labelKey: "nav.rules" },
];
export const CATEGORY_KEYS = [
"categories.item", "categories.pet", "categories.other",
/**
* Категории объявления.
*
* value — то, что уходит на бэкенд и хранится в БД (в т.ч. у уже созданных
* объявлений), поэтому это стабильные значения, а НЕ переводы. Раньше сюда
* клали i18n-ключи и отправляли t(key), из-за чего одно и то же объявление
* получало разный category в зависимости от языка интерфейса.
*/
export const CATEGORIES = [
{ value: "Вещь", labelKey: "categories.item" },
{ value: "Питомец", labelKey: "categories.pet" },
{ value: "Другое", labelKey: "categories.other" },
];
export const CATEGORY_ITEM = "Вещь";
export const CATEGORY_PET = "Питомец";
export const CATEGORY_OTHER = "Другое";
export const EMPTY_FORM = {
type: "loss",
title: "",
@@ -23,11 +37,13 @@ export const EMPTY_FORM = {
category: "",
location: "",
phone: "",
// Согласие на показ номера (152-ФЗ). По умолчанию — «только чат»
phoneVisible: false,
date: "",
address: "",
rulesAccepted: false,
reward: false,
rewardText: ""
rewardText: "",
// Контрольные вопросы находки; пустая строка — одно незаполненное поле
verificationQuestions: [""]
};
export const MAX_PHOTO_SIZE_MB = 5;

Some files were not shown because too many files have changed in this diff Show More