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:
@@ -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 (
|
||||
<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 }.
|
||||
*/
|
||||
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 (
|
||||
<div className="chat-input-area">
|
||||
{attach && (images.length > 0 || 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>
|
||||
))}
|
||||
{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>
|
||||
)}
|
||||
<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={ACCEPT}
|
||||
multiple
|
||||
hidden
|
||||
data-testid="chat-attach-input"
|
||||
onChange={(e) => attach.addFiles(e.target.files)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
className="chat-input"
|
||||
maxLength={MAX_MESSAGE_LENGTH}
|
||||
/>
|
||||
<button type="submit" className="chat-send-btn" disabled={!connected}>
|
||||
<button type="submit" className="chat-send-btn" disabled={!canSend} aria-busy={sending}>
|
||||
➤
|
||||
</button>
|
||||
</form>
|
||||
|
||||
59
src/components/chat/ChatPhotoViewer.jsx
Normal file
59
src/components/chat/ChatPhotoViewer.jsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "../icons/CloseIcon";
|
||||
|
||||
/**
|
||||
* Полноэкранный просмотр фото сообщения: стрелки/точки на десктопе, свайп на
|
||||
* телефоне, Esc и клик по фону — закрыть.
|
||||
*/
|
||||
export default function ChatPhotoViewer({ photos, startIndex = 0, onClose }) {
|
||||
const { t } = useTranslation();
|
||||
const [index, setIndex] = useState(startIndex);
|
||||
const touchStartRef = useRef(null);
|
||||
const count = photos.length;
|
||||
const go = (step) => setIndex((i) => (i + step + count) % count);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
else if (e.key === "ArrowRight" && count > 1) setIndex((i) => (i + 1) % count);
|
||||
else if (e.key === "ArrowLeft" && count > 1) setIndex((i) => (i - 1 + count) % count);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [count, onClose]);
|
||||
|
||||
if (!count) return null;
|
||||
const photo = photos[Math.min(index, count - 1)];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="chat-viewer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onClick={(e) => e.target === e.currentTarget && onClose()}
|
||||
onTouchStart={(e) => { touchStartRef.current = e.touches[0].clientX; }}
|
||||
onTouchEnd={(e) => {
|
||||
const start = touchStartRef.current;
|
||||
touchStartRef.current = null;
|
||||
if (start == null || count < 2) return;
|
||||
const dx = e.changedTouches[0].clientX - start;
|
||||
if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
|
||||
}}
|
||||
>
|
||||
<button type="button" className="chat-viewer-close" onClick={onClose} aria-label={t("common.close")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<img className="chat-viewer-img" src={photo.url} alt="" />
|
||||
{count > 1 && (
|
||||
<>
|
||||
<button type="button" className="chat-viewer-nav chat-viewer-prev" onClick={() => go(-1)}
|
||||
aria-label={t("viewer.prevImage")}>‹</button>
|
||||
<button type="button" className="chat-viewer-nav chat-viewer-next" onClick={() => go(1)}
|
||||
aria-label={t("viewer.nextImage")}>›</button>
|
||||
<div className="chat-viewer-counter">{index + 1} / {count}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
src/components/chat/ChatPhotos.test.jsx
Normal file
86
src/components/chat/ChatPhotos.test.jsx
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Фото в чатах: показ в пузыре и просмотр, отправка сообщения только с фото,
|
||||
* превью «Фото» в списке чатов для сообщения без текста.
|
||||
*/
|
||||
import { createRef } from "react";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import i18n from "../../i18n";
|
||||
import MessageBubble from "./MessageBubble";
|
||||
import ChatInputBar from "./ChatInputBar";
|
||||
import ChatPhotoViewer from "./ChatPhotoViewer";
|
||||
import { getChatDisplayInfo } from "../../utils/chatDisplay";
|
||||
|
||||
const t = i18n.t.bind(i18n);
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
const PHOTOS = [
|
||||
{ id: 1, kind: "PHOTO", url: "https://minio/a.jpg", width: 800, height: 600 },
|
||||
{ id: 2, kind: "PHOTO", url: "https://minio/b.jpg", width: 600, height: 800 },
|
||||
];
|
||||
|
||||
test("фото сообщения показываются и открываются по клику", () => {
|
||||
const onOpenPhoto = jest.fn();
|
||||
const message = { id: 5, content: "", attachments: PHOTOS, createdAt: "2026-10-28T10:00:00" };
|
||||
render(<MessageBubble message={message} isMine onOpenPhoto={onOpenPhoto} />);
|
||||
|
||||
const imgs = screen.getAllByRole("presentation");
|
||||
expect(imgs.map((img) => img.getAttribute("src"))).toEqual(["https://minio/a.jpg", "https://minio/b.jpg"]);
|
||||
|
||||
fireEvent.click(screen.getAllByLabelText("Открыть фото")[1]);
|
||||
expect(onOpenPhoto).toHaveBeenCalledWith(message, 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("привет");
|
||||
});
|
||||
@@ -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 (
|
||||
<div className={`chat-bubble${isMine ? " mine" : ""}`}>
|
||||
{message.content}
|
||||
<div className={`chat-bubble${isMine ? " mine" : ""}${photos.length ? " has-photos" : ""}`}>
|
||||
{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?.(message, 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>}
|
||||
{time && <div className="chat-bubble-time">{time}</div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user