diff --git a/src/components/chat/ChatInputBar.jsx b/src/components/chat/ChatInputBar.jsx index 82af217..0d8d478 100644 --- a/src/components/chat/ChatInputBar.jsx +++ b/src/components/chat/ChatInputBar.jsx @@ -1,24 +1,95 @@ +import { ACCEPT } from "../../hooks/useImageUpload"; +import CloseIcon from "../icons/CloseIcon"; + // Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде const MAX_MESSAGE_LENGTH = 4000; +function PaperclipIcon() { + return ( + + ); +} + +/** + * Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото над полем + * и вставка картинок из буфера обмена. attach: { images, addFiles, removeImage, + * fileInputRef, compressing, error, disabled, label, removeLabel }. + */ export default function ChatInputBar({ input, onInputChange, onSend, connected, placeholder, + attach, + sending = false, }) { + const images = attach?.images ?? []; + const canSend = connected && !sending && !attach?.compressing && (input.trim() || images.length > 0); + + 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 (
+ {attach && (images.length > 0 || attach.compressing || attach.error) && ( +
+ {images.map((img) => ( +
+ + {!sending && ( + + )} +
+ ))} + {attach.compressing && ( +
+ )} + {attach.error &&
{attach.error}
} +
+ )}
+ {attach && ( + <> + + attach.addFiles(e.target.files)} + /> + + )} onInputChange(e.target.value)} + onPaste={handlePaste} placeholder={placeholder} className="chat-input" maxLength={MAX_MESSAGE_LENGTH} /> -
diff --git a/src/components/chat/ChatPhotoViewer.jsx b/src/components/chat/ChatPhotoViewer.jsx new file mode 100644 index 0000000..90605b0 --- /dev/null +++ b/src/components/chat/ChatPhotoViewer.jsx @@ -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 ( +
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); + }} + > + + + {count > 1 && ( + <> + + +
{index + 1} / {count}
+ + )} +
+ ); +} diff --git a/src/components/chat/ChatPhotos.test.jsx b/src/components/chat/ChatPhotos.test.jsx new file mode 100644 index 0000000..40685f3 --- /dev/null +++ b/src/components/chat/ChatPhotos.test.jsx @@ -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(); + + 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(message, 1); +}); + +test("истёкшая ссылка на фото сообщает об ошибке для обновления", () => { + const onPhotoError = jest.fn(); + const message = { id: 5, content: "вот", attachments: [PHOTOS[0]] }; + render(); + + 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( + {}} onSend={() => {}} connected placeholder="" attach={attach} />); + + expect(screen.getByRole("button", { name: "➤" })).toBeEnabled(); + + fireEvent.click(screen.getByLabelText("Убрать фото")); + expect(attach.removeImage).toHaveBeenCalledWith("img-1"); + + rerender( {}} onSend={() => {}} connected placeholder="" + attach={{ ...attach, images: [] }} />); + expect(screen.getByRole("button", { name: "➤" })).toBeDisabled(); +}); + +test("просмотр листает фото и закрывается по Esc", () => { + const onClose = jest.fn(); + render(); + + 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("привет"); +}); diff --git a/src/components/chat/MessageBubble.jsx b/src/components/chat/MessageBubble.jsx index b6e269d..8c15f17 100644 --- a/src/components/chat/MessageBubble.jsx +++ b/src/components/chat/MessageBubble.jsx @@ -1,13 +1,44 @@ import { useTranslation } from "react-i18next"; import { formatMessageTime } from "../../utils/chatDisplay"; -export default function MessageBubble({ message, isMine }) { - const { i18n } = useTranslation(); +/** + * Пузырь сообщения. Фото (message.attachments) — сеткой над текстом; клик + * открывает просмотр. width/height приходят с бэкенда: место под фото + * резервируется сразу, и лента не прыгает, пока картинки грузятся. + */ +export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoError }) { + const { t, i18n } = useTranslation(); const time = formatMessageTime(message.createdAt, i18n.language); + const photos = Array.isArray(message.attachments) ? message.attachments : []; + const single = photos.length === 1; return ( -
- {message.content} +
+ {photos.length > 0 && ( +
+ {photos.map((photo, i) => ( + + ))} +
+ )} + {message.content &&
{message.content}
} {time &&
{time}
}
); diff --git a/src/hooks/useChats.js b/src/hooks/useChats.js index c7cf8f9..cb755cc 100644 --- a/src/hooks/useChats.js +++ b/src/hooks/useChats.js @@ -98,7 +98,39 @@ export function useChats() { } }, [clearChatUnread]); - return { chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead }; + /** + * Сообщение с фото (и необязательным текстом) — через REST: файлы по + * WebSocket не передать. Возвращает сохранённое сообщение; собеседнику + * (и нам же) оно придёт и по сокету — дубль отсекается по id. + */ + const sendPhotoMessage = useCallback(async (chatId, content, files) => { + const data = new FormData(); + if (content) data.append("content", content); + files.forEach((file) => data.append("files", file, file.name || "photo.jpg")); + const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`, { + method: "POST", + body: data, + }); + if (!res.ok) { + const err = await readApiError(res); + console.warn("sendPhotoMessage failed:", err.status, err.serverMessage); + throw err; + } + return res.json(); + }, []); + + /** Свежая ссылка на фото, если выданная вместе с сообщением истекла. */ + const refreshAttachmentUrl = useCallback(async (chatId, attachmentId) => { + const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/attachments/${attachmentId}/url`); + if (!res.ok) throw new Error(`Error ${res.status}`); + const { url } = await res.json(); + return url; + }, []); + + return { + chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead, + sendPhotoMessage, refreshAttachmentUrl, + }; } function chatWithUrl(otherUserId, postId, suffix = "") { diff --git a/src/hooks/useImageUpload.js b/src/hooks/useImageUpload.js index ed647c2..0721904 100644 --- a/src/hooks/useImageUpload.js +++ b/src/hooks/useImageUpload.js @@ -122,6 +122,17 @@ export function useImageUpload(existingUrls = []) { }); }, []); + /** Убирает все выбранные фото (например, после отправки сообщения). */ + const clearImages = useCallback(() => { + setImages(prev => { + prev.forEach(img => { + if (!img.isExisting && img.preview) URL.revokeObjectURL(img.preview); + }); + return []; + }); + setImgError(""); + }, []); + const getFilesForUpload = useCallback(() => { return images.filter(i => !i.isExisting).map(i => i.file); }, [images]); @@ -156,6 +167,7 @@ export function useImageUpload(existingUrls = []) { handleFileChange, addFiles, removeImage, + clearImages, getFilesForUpload, getExistingUrlsToKeep, }; diff --git a/src/locales/en.json b/src/locales/en.json index 901dade..58a97de 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -216,6 +216,11 @@ "deleteChat": "Delete chat", "confirmDeleteChat": "Are you sure you want to delete this chat?", "user": "User", + "photoPreview": "Photo", + "attachPhoto": "Attach photo", + "removePhoto": "Remove photo", + "openPhoto": "Open photo", + "tooManyPhotos": "No more than {{max}} photos per message", "postInfo": "Listing for this chat", "postRemoved": "Listing deleted", "postClosed": "Closed", diff --git a/src/locales/ru.json b/src/locales/ru.json index c606c78..f463070 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -216,6 +216,11 @@ "deleteChat": "Удалить чат", "confirmDeleteChat": "Вы уверены, что хотите удалить этот чат?", "user": "Пользователь", + "photoPreview": "Фото", + "attachPhoto": "Прикрепить фото", + "removePhoto": "Убрать фото", + "openPhoto": "Открыть фото", + "tooManyPhotos": "Не больше {{max}} фото в одном сообщении", "postInfo": "Объявление этого чата", "postRemoved": "Объявление удалено", "postClosed": "Закрыто", diff --git a/src/pages/ChatPage.jsx b/src/pages/ChatPage.jsx index c38947f..b586cb7 100644 --- a/src/pages/ChatPage.jsx +++ b/src/pages/ChatPage.jsx @@ -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 } = {}) {
{t('chat.noMessages')}
)} {messages.map((m) => ( - + setViewer({ photos: msg.attachments, index })} + onPhotoError={handlePhotoError} + /> ))}
@@ -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'), + }} />
+ {viewer && ( + setViewer(null)} /> + )} + {showPost && ( 0 ? `📷 ${t('chat.photoPreview')}` : ""; + const preview = getLastMessageText(chat) || photoPreview || t('chat.noMessages'); return { title, imgSrc, emoji, unreadCount, preview }; } \ No newline at end of file