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>
This commit is contained in:
SlimusMinus
2026-10-28 22:26:44 +03:00
parent 0380bc8985
commit b7b30575a2
12 changed files with 537 additions and 11 deletions

View File

@@ -13,11 +13,16 @@ 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 PostDetailModal from "../components/PostDetailModal";
import { POST_STATUS_CLOSED } from "../config/postConstants";
import { useImageUpload } from "../hooks/useImageUpload";
import Toast from "../components/Toast";
// Тот же лимит, что ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE на бэкенде
const MAX_PHOTOS_PER_MESSAGE = 10;
/**
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
@@ -33,7 +38,7 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
const draft = chatId ? null : location.state;
const [startingChat, setStartingChat] = useState(false);
const { fetchMessages, markAsRead, startChat } = useChats();
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, refreshAttachmentUrl } = useChats();
const { clearChatUnread } = useUnread();
const { user, isAuthenticated } = useAuthContext();
const [messages, setMessages] = useState([]);
@@ -41,6 +46,13 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
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("");
// id вложений, для которых уже запрашивали свежую ссылку, — без повторов по кругу
const refreshedPhotosRef = useRef(new Set());
const messagesEndRef = useRef(null);
const pageRef = useRef(null);
@@ -107,9 +119,17 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const header = page?.querySelector(".chat-header");
const inputArea = page?.querySelector(".chat-input-area");
if (!header || !inputArea) return;
const list = page.querySelector(".chat-messages");
let inputHeight = inputArea.offsetHeight;
const update = () => {
// Поле ввода выросло (появились превью фото), а пользователь был внизу
// ленты — оставляем его внизу, иначе последнее сообщение уйдёт под превью
const grew = inputArea.offsetHeight > inputHeight;
const atBottom = list && list.scrollHeight - list.scrollTop - list.clientHeight < inputArea.offsetHeight + 80;
inputHeight = inputArea.offsetHeight;
page.style.setProperty("--chat-header-height", `${header.offsetHeight}px`);
page.style.setProperty("--chat-input-height", `${inputArea.offsetHeight}px`);
page.style.setProperty("--chat-input-height", `${inputHeight}px`);
if (grew && atBottom) list.scrollTop = list.scrollHeight;
};
update();
const ro = new ResizeObserver(update);
@@ -125,6 +145,25 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const handleSend = useCallback((e) => {
e.preventDefault();
const trimmed = input.trim();
const photos = draft ? [] : upload.getFilesForUpload();
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) {
@@ -149,7 +188,31 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
}
setInput("");
onActivity?.();
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity]);
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity,
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage]);
const addPhotos = useCallback((fileList) => {
const files = Array.from(fileList || []);
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]);
// Ссылка на фото временная: если чат долго открыт и она истекла, берём свежую
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) => setMessages((prev) => prev.map((m) => (m.id !== message.id ? m : {
...m,
attachments: m.attachments.map((a) => (a.id === photo.id ? { ...a, url } : a)),
}))))
.catch(() => {});
}, [chatId, refreshAttachmentUrl]);
const post = draft ? draft.post : getPostForChat(chatId);
const postImg = getImageUrl(post?.images?.[0]);
@@ -187,7 +250,13 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
<div className="chat-empty">{t('chat.noMessages')}</div>
)}
{messages.map((m) => (
<MessageBubble key={m.id} message={m} isMine={m.senderId === myUserId} />
<MessageBubble
key={m.id}
message={m}
isMine={m.senderId === myUserId}
onOpenPhoto={(msg, index) => setViewer({ photos: msg.attachments, index })}
onPhotoError={handlePhotoError}
/>
))}
<div ref={messagesEndRef} />
</div>
@@ -198,9 +267,25 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
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,
error: photoLimitError || upload.imgError,
label: t('chat.attachPhoto'),
removeLabel: t('chat.removePhoto'),
}}
/>
</div>
{viewer && (
<ChatPhotoViewer photos={viewer.photos} startIndex={viewer.index} onClose={() => setViewer(null)} />
)}
{showPost && (
<PostDetailModal
postId={postId}