- 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>
436 lines
20 KiB
JavaScript
436 lines
20 KiB
JavaScript
import { useState, useEffect, useCallback, useRef } from "react";
|
||
import { useParams, useNavigate, useLocation } from "react-router-dom";
|
||
import { useTranslation } from 'react-i18next';
|
||
import { useChats } from "../hooks/useChats";
|
||
import { useChatSocket } from "../hooks/useChatSocket";
|
||
import { getPostForChat } from "../stores/chatPostStore";
|
||
import { sortMessages } from "../utils/chatDisplay";
|
||
import { setActiveChatId } from "../stores/activeChatStore";
|
||
import { useUnread } from "../context/UnreadContext";
|
||
import { useAuthContext } from "../context/AuthContext";
|
||
import { describeApiError } from "../api/apiErrors";
|
||
import { getImageUrl } from "../config/authConstants";
|
||
import ChatHeader from "../components/chat/ChatHeader";
|
||
import MessageBubble from "../components/chat/MessageBubble";
|
||
import ChatInputBar from "../components/chat/ChatInputBar";
|
||
import ChatPhotoViewer from "../components/chat/ChatPhotoViewer";
|
||
import ChatPostMeta from "../components/chat/ChatPostMeta";
|
||
import ChatSafetyNotice from "../components/chat/ChatSafetyNotice";
|
||
import ClaimForm from "../components/chat/ClaimForm";
|
||
import VerificationPanel from "../components/chat/VerificationPanel";
|
||
import PostDetailModal from "../components/PostDetailModal";
|
||
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
||
import { ACCEPT as IMAGE_ACCEPT, useImageUpload } from "../hooks/useImageUpload";
|
||
import { VIDEO_TYPES, useVideoAttachment } from "../hooks/useVideoAttachment";
|
||
import Toast from "../components/Toast";
|
||
|
||
// Тот же лимит, что ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE на бэкенде
|
||
const MAX_PHOTOS_PER_MESSAGE = 10;
|
||
|
||
/**
|
||
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
|
||
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
|
||
* а onActivity сообщает списку чатов, что превью пора обновить.
|
||
*
|
||
* @param {{ embedded?: boolean, onActivity?: () => void }} [props]
|
||
*/
|
||
export default function ChatPage({ embedded = false, onActivity } = {}) {
|
||
const { t } = useTranslation();
|
||
const { chatId } = useParams();
|
||
const navigate = useNavigate();
|
||
const location = useLocation();
|
||
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
|
||
const draft = chatId ? null : location.state;
|
||
const [startingChat, setStartingChat] = useState(false);
|
||
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl,
|
||
fetchChat, claimPost, decideVerification } = useChats();
|
||
const { clearChatUnread } = useUnread();
|
||
const { user, isAuthenticated } = useAuthContext();
|
||
const [messages, setMessages] = useState([]);
|
||
const [input, setInput] = useState("");
|
||
const [loadError, setLoadError] = useState("");
|
||
const [sendError, setSendError] = useState("");
|
||
const [showPost, setShowPost] = useState(false);
|
||
const [sendingPhotos, setSendingPhotos] = useState(false);
|
||
const [viewer, setViewer] = useState(null);
|
||
const upload = useImageUpload();
|
||
const { addFiles: addUploadFiles } = upload;
|
||
const [photoLimitError, setPhotoLimitError] = useState("");
|
||
const videoAttach = useVideoAttachment();
|
||
const { selectVideo } = videoAttach;
|
||
// Прогресс загрузки видео в хранилище, 0..1; null — загрузки нет
|
||
const [videoProgress, setVideoProgress] = useState(null);
|
||
// Чат с бэкенда: статус проверки ответов на вопросы объявления и дата регистрации собеседника
|
||
const [chatInfo, setChatInfo] = useState(null);
|
||
const [deciding, setDeciding] = useState(false);
|
||
// Черновик к объявлению с контрольными вопросами: вместо поля ввода — форма ответов
|
||
const claimQuestions = draft?.questions?.length ? draft.questions : null;
|
||
// id вложений, для которых уже запрашивали свежую ссылку, — без повторов по кругу
|
||
const refreshedPhotosRef = useRef(new Set());
|
||
const messagesEndRef = useRef(null);
|
||
const pageRef = useRef(null);
|
||
|
||
const myUserId = user?.id;
|
||
|
||
/**
|
||
* Мержит сообщение по id — защита от дублей (REST + WS эхо). Уже известное
|
||
* сообщение заменяется: так приходит видео, которое закончило обрабатываться.
|
||
*/
|
||
const addMessage = useCallback((msg) => {
|
||
setMessages((prev) => {
|
||
if (msg.id != null && prev.some((m) => m.id === msg.id)) {
|
||
return prev.map((m) => (m.id === msg.id ? { ...m, ...msg } : m));
|
||
}
|
||
return sortMessages([...prev, msg]);
|
||
});
|
||
}, []);
|
||
|
||
const handleIncoming = useCallback((msg) => {
|
||
addMessage(msg);
|
||
// Автор подтвердил или отклонил ответы: снимаем или оставляем блокировку ввода
|
||
if (msg.kind === "VERIFICATION" && msg.verificationStatus) {
|
||
setChatInfo((prev) => (prev ? { ...prev, verificationStatus: msg.verificationStatus } : prev));
|
||
}
|
||
}, [addMessage]);
|
||
|
||
// Сервер отклонил отправку (пустое/длинное сообщение, нет доступа к чату)
|
||
const handleSocketError = useCallback((text) => {
|
||
setSendError(text || t('chats.sendRejected'));
|
||
}, [t]);
|
||
|
||
const { sendMessage, connected } = useChatSocket(isAuthenticated ? chatId : null, handleIncoming, handleSocketError);
|
||
|
||
// /chats/new без данных черновика (например, после перезагрузки) — открывать нечего.
|
||
// Без входа (вышли, сессия истекла) — на список чатов, там предложат войти.
|
||
useEffect(() => {
|
||
if (!isAuthenticated || (!chatId && !draft)) navigate("/chats", { replace: true });
|
||
}, [chatId, draft, navigate, isAuthenticated]);
|
||
|
||
useEffect(() => {
|
||
if (!chatId) return;
|
||
|
||
setActiveChatId(chatId);
|
||
setLoadError("");
|
||
|
||
fetchMessages(chatId)
|
||
.then((list) => {
|
||
// Мержим историю с уже пришедшими по сокету сообщениями,
|
||
// а не затираем их — иначе можно потерять сообщение, пришедшее
|
||
// по WS, пока REST-запрос ещё летел. История приходит DESC (новые
|
||
// сверху), поэтому всегда сортируем по времени — иначе после
|
||
// обновления страницы все сообщения последнего собеседника
|
||
// оказываются наверху и идут подряд.
|
||
setMessages((prev) => {
|
||
const byId = new Map(list.map((m) => [m.id, m]));
|
||
const extra = prev.filter((m) => !byId.has(m.id));
|
||
return sortMessages([...list, ...extra]);
|
||
});
|
||
})
|
||
.catch(() => setLoadError(t('chats.loadError')));
|
||
|
||
setChatInfo(null);
|
||
fetchChat(chatId).then(setChatInfo).catch(() => {});
|
||
|
||
markAsRead(chatId);
|
||
clearChatUnread(chatId);
|
||
|
||
return () => setActiveChatId(null);
|
||
}, [chatId, fetchMessages, markAsRead, clearChatUnread, fetchChat, t]);
|
||
|
||
// Шапка и поле ввода лежат поверх ленты сообщений — меряем их высоту в
|
||
// CSS-переменные --chat-header-height / --chat-input-height, чтобы первое
|
||
// и последнее сообщения не прятались под ними.
|
||
useEffect(() => {
|
||
const page = pageRef.current;
|
||
const header = page?.querySelector(".chat-header");
|
||
const inputArea = page?.querySelector(".chat-input-area");
|
||
if (!header || !inputArea) return;
|
||
const list = page.querySelector(".chat-messages");
|
||
let inputHeight = inputArea.offsetHeight;
|
||
const update = () => {
|
||
// Поле ввода выросло (появились превью фото), а пользователь был внизу
|
||
// ленты — оставляем его внизу, иначе последнее сообщение уйдёт под превью
|
||
const grew = inputArea.offsetHeight > inputHeight;
|
||
const atBottom = list && list.scrollHeight - list.scrollTop - list.clientHeight < inputArea.offsetHeight + 80;
|
||
inputHeight = inputArea.offsetHeight;
|
||
page.style.setProperty("--chat-header-height", `${header.offsetHeight}px`);
|
||
page.style.setProperty("--chat-input-height", `${inputHeight}px`);
|
||
if (grew && atBottom) list.scrollTop = list.scrollHeight;
|
||
};
|
||
update();
|
||
const ro = new ResizeObserver(update);
|
||
ro.observe(header);
|
||
ro.observe(inputArea);
|
||
return () => ro.disconnect();
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||
}, [messages]);
|
||
|
||
const handleSend = useCallback((e) => {
|
||
e.preventDefault();
|
||
const trimmed = input.trim();
|
||
const photos = draft ? [] : upload.getFilesForUpload();
|
||
|
||
const video = draft ? null : videoAttach.video;
|
||
if (video) {
|
||
if (sendingPhotos) return;
|
||
setSendingPhotos(true);
|
||
setVideoProgress(0);
|
||
sendVideoMessage(chatId, trimmed, video.file, setVideoProgress)
|
||
.then((msg) => {
|
||
addMessage(msg);
|
||
setInput("");
|
||
videoAttach.clearVideo();
|
||
onActivity?.();
|
||
})
|
||
// 429 — лимит видео; 400 — формат, размер; сбой загрузки в хранилище
|
||
.catch((err) => setSendError(describeApiError(err, t('chat.videoSendError'))))
|
||
.finally(() => {
|
||
setSendingPhotos(false);
|
||
setVideoProgress(null);
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (photos.length > 0) {
|
||
if (sendingPhotos || upload.compressing) return;
|
||
setSendingPhotos(true);
|
||
sendPhotoMessage(chatId, trimmed, photos)
|
||
.then((msg) => {
|
||
addMessage(msg);
|
||
setInput("");
|
||
upload.clearImages();
|
||
setPhotoLimitError("");
|
||
onActivity?.();
|
||
})
|
||
// 429 — лимит отправки фото; 400 — не картинка, слишком много фото и т.п.
|
||
.catch((err) => setSendError(describeApiError(err, t('chats.sendError'))))
|
||
.finally(() => setSendingPhotos(false));
|
||
return;
|
||
}
|
||
|
||
if (!trimmed) return;
|
||
|
||
if (draft) {
|
||
if (startingChat) return;
|
||
setStartingChat(true);
|
||
startChat(draft.otherUserId, draft.postId, trimmed, draft.post)
|
||
.then((chat) => {
|
||
setInput("");
|
||
onActivity?.();
|
||
navigate(`/chats/${chat.id}`, { replace: true });
|
||
})
|
||
// 429 — лимит начала чатов; 400 — чат с собой, чужое объявление и т.п.
|
||
.catch((err) => setSendError(describeApiError(err, t('chats.sendError'))))
|
||
.finally(() => setStartingChat(false));
|
||
return;
|
||
}
|
||
|
||
const sent = sendMessage(trimmed);
|
||
if (!sent) {
|
||
setSendError(t('chats.sendError'));
|
||
return;
|
||
}
|
||
setInput("");
|
||
onActivity?.();
|
||
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity,
|
||
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage, videoAttach, sendVideoMessage]);
|
||
|
||
// «Это моё»: чат создаётся вместе с ответами, дальше ждём решения автора
|
||
const handleClaim = useCallback((answers) => {
|
||
if (startingChat) return;
|
||
setStartingChat(true);
|
||
claimPost(draft.postId, answers, draft.post)
|
||
.then((chat) => {
|
||
onActivity?.();
|
||
navigate(`/chats/${chat.id}`, { replace: true });
|
||
})
|
||
// 429 — лимит заявок; 409 — уже отвечали; 400 — не все ответы
|
||
.catch((err) => setSendError(describeApiError(err, t('chat.claimError'))))
|
||
.finally(() => setStartingChat(false));
|
||
}, [startingChat, claimPost, draft, onActivity, navigate, t]);
|
||
|
||
const handleDecide = useCallback((approved) => {
|
||
if (deciding) return;
|
||
setDeciding(true);
|
||
decideVerification(chatId, approved)
|
||
.then((msg) => {
|
||
addMessage(msg);
|
||
setChatInfo((prev) => ({ ...prev, verificationStatus: msg.verificationStatus }));
|
||
onActivity?.();
|
||
})
|
||
.catch((err) => setSendError(describeApiError(err, t('chat.verifyError'))))
|
||
.finally(() => setDeciding(false));
|
||
}, [deciding, decideVerification, chatId, addMessage, onActivity, t]);
|
||
|
||
/**
|
||
* Выбор файлов: фото (до 10) или одно видео. Видео уходит отдельным
|
||
* сообщением — вместе с фото его не отправить.
|
||
*/
|
||
const addPhotos = useCallback((fileList) => {
|
||
const files = Array.from(fileList || []);
|
||
const videos = files.filter((f) => f.type.startsWith("video/"));
|
||
if (videos.length > 0) {
|
||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||
if (videos.length > 1 || files.length > videos.length || upload.images.length > 0) {
|
||
setPhotoLimitError(t('chat.videoSeparately'));
|
||
return;
|
||
}
|
||
setPhotoLimitError("");
|
||
selectVideo(videos[0]);
|
||
return;
|
||
}
|
||
if (videoAttach.video) {
|
||
setPhotoLimitError(t('chat.videoSeparately'));
|
||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||
return;
|
||
}
|
||
if (upload.images.length + files.length > MAX_PHOTOS_PER_MESSAGE) {
|
||
setPhotoLimitError(t('chat.tooManyPhotos', { max: MAX_PHOTOS_PER_MESSAGE }));
|
||
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
|
||
return;
|
||
}
|
||
setPhotoLimitError("");
|
||
addUploadFiles(files);
|
||
}, [upload.images.length, upload.fileInputRef, addUploadFiles, t, selectVideo, videoAttach.video]);
|
||
|
||
// Ссылки на фото и видео временные: если чат долго открыт и ссылка истекла, берём свежую
|
||
const handlePhotoError = useCallback((message, photo) => {
|
||
if (!chatId || photo.id == null || refreshedPhotosRef.current.has(photo.id)) return;
|
||
refreshedPhotosRef.current.add(photo.id);
|
||
refreshAttachmentUrl(chatId, photo.id)
|
||
.then(({ url, posterUrl }) => setMessages((prev) => prev.map((m) => (m.id !== message.id ? m : {
|
||
...m,
|
||
attachments: m.attachments.map((a) => (a.id === photo.id ? { ...a, url, posterUrl } : a)),
|
||
}))))
|
||
.catch(() => {});
|
||
}, [chatId, refreshAttachmentUrl]);
|
||
|
||
const post = draft ? draft.post : (getPostForChat(chatId) || chatInfo?.post);
|
||
const verificationStatus = chatInfo?.verificationStatus ?? null;
|
||
const isClaimant = chatInfo?.claimantId != null && String(chatInfo.claimantId) === String(myUserId);
|
||
// Заявитель пишет только после подтверждения ответов (бэкенд отклонит и сам)
|
||
const inputLocked = isClaimant && verificationStatus != null && verificationStatus !== "APPROVED";
|
||
const postImg = getImageUrl(post?.images?.[0]);
|
||
const postId = post?.id ?? draft?.postId;
|
||
|
||
// «Перейти к объявлению» — на карту с фокусом на нём (тот же URL, что у
|
||
// кнопки адреса в ленте). Без координат на карте фокусироваться не на чем.
|
||
const hasCoords = (ad) => ad?.latitude != null && ad?.longitude != null
|
||
&& Number.isFinite(Number(ad.latitude)) && Number.isFinite(Number(ad.longitude));
|
||
const openOnMap = (ad) => {
|
||
if (!hasCoords(ad)) return;
|
||
const params = new URLSearchParams({ view: "map", post: String(ad.id), lat: String(ad.latitude), lng: String(ad.longitude) });
|
||
navigate(`/feed?${params.toString()}`);
|
||
};
|
||
|
||
const content = (
|
||
<>
|
||
<div className={`chat-page chat-page--open${embedded ? " chat-page--embedded" : ""}`} ref={pageRef}>
|
||
<ChatHeader
|
||
title={post?.title || t('chat.title')}
|
||
onBack={() => navigate("/chats")}
|
||
subtitle={<ChatPostMeta post={post} t={t} className="chat-header-meta" />}
|
||
onInfo={postId != null ? () => setShowPost(true) : undefined}
|
||
infoLabel={t('chat.postInfo')}
|
||
avatar={postImg ? (
|
||
<img src={postImg} alt="" className="chat-header-avatar-img" />
|
||
) : (
|
||
post?.emoji || "📋"
|
||
)}
|
||
/>
|
||
|
||
<div className="chat-messages">
|
||
<ChatSafetyNotice key={chatId ?? "draft"} chatId={chatId} otherUserCreatedAt={chatInfo?.otherUserCreatedAt} t={t} />
|
||
{loadError && <div className="chat-empty">{loadError}</div>}
|
||
{claimQuestions && (
|
||
<ClaimForm questions={claimQuestions} onSubmit={handleClaim} sending={startingChat} t={t} />
|
||
)}
|
||
{!loadError && !claimQuestions && messages.length === 0 && (
|
||
<div className="chat-empty">{t('chat.noMessages')}</div>
|
||
)}
|
||
{messages.map((m) => (
|
||
<MessageBubble
|
||
key={m.id}
|
||
message={m}
|
||
isMine={m.senderId === myUserId}
|
||
onOpenPhoto={(photos, index) => setViewer({ photos, index })}
|
||
onPhotoError={handlePhotoError}
|
||
/>
|
||
))}
|
||
<div ref={messagesEndRef} />
|
||
</div>
|
||
|
||
<ChatInputBar
|
||
locked={!!claimQuestions || inputLocked}
|
||
notice={(
|
||
<VerificationPanel
|
||
status={verificationStatus}
|
||
isClaimant={isClaimant}
|
||
postId={postId}
|
||
phoneVisible={!!(chatInfo?.post?.phoneVisible ?? post?.phoneVisible)}
|
||
onDecide={handleDecide}
|
||
deciding={deciding}
|
||
t={t}
|
||
/>
|
||
)}
|
||
input={input}
|
||
onInputChange={setInput}
|
||
onSend={handleSend}
|
||
connected={draft ? !startingChat : connected}
|
||
placeholder={t('chat.messagePlaceholder')}
|
||
sending={sendingPhotos}
|
||
/* В черновике (/chats/new) чата ещё нет — фото можно со второго сообщения */
|
||
attach={draft ? undefined : {
|
||
images: upload.images,
|
||
addFiles: addPhotos,
|
||
removeImage: upload.removeImage,
|
||
fileInputRef: upload.fileInputRef,
|
||
compressing: upload.compressing || videoAttach.checking,
|
||
error: photoLimitError || videoAttach.error || upload.imgError,
|
||
accept: [IMAGE_ACCEPT, ...VIDEO_TYPES].join(","),
|
||
video: videoAttach.video,
|
||
removeVideo: videoAttach.clearVideo,
|
||
videoProgress,
|
||
label: t('chat.attachMedia'),
|
||
removeLabel: t('chat.removePhoto'),
|
||
}}
|
||
/>
|
||
</div>
|
||
|
||
{viewer && (
|
||
<ChatPhotoViewer photos={viewer.photos} startIndex={viewer.index} onClose={() => setViewer(null)} />
|
||
)}
|
||
|
||
{showPost && (
|
||
<PostDetailModal
|
||
postId={postId}
|
||
onClose={() => setShowPost(false)}
|
||
onLocationClick={openOnMap}
|
||
compact={false}
|
||
hideContact
|
||
fallbackTitle={post?.title}
|
||
footer={(ad) => ad.status !== POST_STATUS_CLOSED && hasCoords(ad) && (
|
||
<div className="chat-post-modal-actions">
|
||
<button type="button" className="chat-post-open-btn" onClick={() => openOnMap(ad)}>
|
||
{t('chat.showOnMap')}
|
||
</button>
|
||
</div>
|
||
)}
|
||
/>
|
||
)}
|
||
|
||
{sendError && (
|
||
<Toast
|
||
message={sendError}
|
||
type="error"
|
||
onDismiss={() => setSendError("")}
|
||
/>
|
||
)}
|
||
</>
|
||
);
|
||
|
||
return embedded ? content : <div className="f-app">{content}</div>;
|
||
} |