Merge pull request #124 from SlimusMinus/feat-chat_photos
All checks were successful
deploy-frontend / deploy (push) Successful in 56s
All checks were successful
deploy-frontend / deploy (push) Successful in 56s
Send and view photos in chats
This commit is contained in:
@@ -1,24 +1,95 @@
|
|||||||
|
import { ACCEPT } from "../../hooks/useImageUpload";
|
||||||
|
import CloseIcon from "../icons/CloseIcon";
|
||||||
|
|
||||||
// Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде
|
// Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде
|
||||||
const MAX_MESSAGE_LENGTH = 4000;
|
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({
|
export default function ChatInputBar({
|
||||||
input,
|
input,
|
||||||
onInputChange,
|
onInputChange,
|
||||||
onSend,
|
onSend,
|
||||||
connected,
|
connected,
|
||||||
placeholder,
|
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 (
|
return (
|
||||||
<div className="chat-input-area">
|
<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">
|
<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
|
<input
|
||||||
value={input}
|
value={input}
|
||||||
onChange={(e) => onInputChange(e.target.value)}
|
onChange={(e) => onInputChange(e.target.value)}
|
||||||
|
onPaste={handlePaste}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
className="chat-input"
|
className="chat-input"
|
||||||
maxLength={MAX_MESSAGE_LENGTH}
|
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>
|
</button>
|
||||||
</form>
|
</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 { useTranslation } from "react-i18next";
|
||||||
import { formatMessageTime } from "../../utils/chatDisplay";
|
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 time = formatMessageTime(message.createdAt, i18n.language);
|
||||||
|
const photos = Array.isArray(message.attachments) ? message.attachments : [];
|
||||||
|
const single = photos.length === 1;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`chat-bubble${isMine ? " mine" : ""}`}>
|
<div className={`chat-bubble${isMine ? " mine" : ""}${photos.length ? " has-photos" : ""}`}>
|
||||||
{message.content}
|
{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>}
|
{time && <div className="chat-bubble-time">{time}</div>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -98,7 +98,39 @@ export function useChats() {
|
|||||||
}
|
}
|
||||||
}, [clearChatUnread]);
|
}, [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 = "") {
|
function chatWithUrl(otherUserId, postId, suffix = "") {
|
||||||
|
|||||||
@@ -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(() => {
|
const getFilesForUpload = useCallback(() => {
|
||||||
return images.filter(i => !i.isExisting).map(i => i.file);
|
return images.filter(i => !i.isExisting).map(i => i.file);
|
||||||
}, [images]);
|
}, [images]);
|
||||||
@@ -156,6 +167,7 @@ export function useImageUpload(existingUrls = []) {
|
|||||||
handleFileChange,
|
handleFileChange,
|
||||||
addFiles,
|
addFiles,
|
||||||
removeImage,
|
removeImage,
|
||||||
|
clearImages,
|
||||||
getFilesForUpload,
|
getFilesForUpload,
|
||||||
getExistingUrlsToKeep,
|
getExistingUrlsToKeep,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -216,6 +216,11 @@
|
|||||||
"deleteChat": "Delete chat",
|
"deleteChat": "Delete chat",
|
||||||
"confirmDeleteChat": "Are you sure you want to delete this chat?",
|
"confirmDeleteChat": "Are you sure you want to delete this chat?",
|
||||||
"user": "User",
|
"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",
|
"postInfo": "Listing for this chat",
|
||||||
"postRemoved": "Listing deleted",
|
"postRemoved": "Listing deleted",
|
||||||
"postClosed": "Closed",
|
"postClosed": "Closed",
|
||||||
|
|||||||
@@ -216,6 +216,11 @@
|
|||||||
"deleteChat": "Удалить чат",
|
"deleteChat": "Удалить чат",
|
||||||
"confirmDeleteChat": "Вы уверены, что хотите удалить этот чат?",
|
"confirmDeleteChat": "Вы уверены, что хотите удалить этот чат?",
|
||||||
"user": "Пользователь",
|
"user": "Пользователь",
|
||||||
|
"photoPreview": "Фото",
|
||||||
|
"attachPhoto": "Прикрепить фото",
|
||||||
|
"removePhoto": "Убрать фото",
|
||||||
|
"openPhoto": "Открыть фото",
|
||||||
|
"tooManyPhotos": "Не больше {{max}} фото в одном сообщении",
|
||||||
"postInfo": "Объявление этого чата",
|
"postInfo": "Объявление этого чата",
|
||||||
"postRemoved": "Объявление удалено",
|
"postRemoved": "Объявление удалено",
|
||||||
"postClosed": "Закрыто",
|
"postClosed": "Закрыто",
|
||||||
|
|||||||
@@ -13,11 +13,16 @@ import { getImageUrl } from "../config/authConstants";
|
|||||||
import ChatHeader from "../components/chat/ChatHeader";
|
import ChatHeader from "../components/chat/ChatHeader";
|
||||||
import MessageBubble from "../components/chat/MessageBubble";
|
import MessageBubble from "../components/chat/MessageBubble";
|
||||||
import ChatInputBar from "../components/chat/ChatInputBar";
|
import ChatInputBar from "../components/chat/ChatInputBar";
|
||||||
|
import ChatPhotoViewer from "../components/chat/ChatPhotoViewer";
|
||||||
import ChatPostMeta from "../components/chat/ChatPostMeta";
|
import ChatPostMeta from "../components/chat/ChatPostMeta";
|
||||||
import PostDetailModal from "../components/PostDetailModal";
|
import PostDetailModal from "../components/PostDetailModal";
|
||||||
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
||||||
|
import { useImageUpload } from "../hooks/useImageUpload";
|
||||||
import Toast from "../components/Toast";
|
import Toast from "../components/Toast";
|
||||||
|
|
||||||
|
// Тот же лимит, что ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE на бэкенде
|
||||||
|
const MAX_PHOTOS_PER_MESSAGE = 10;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
|
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
|
||||||
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
|
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
|
||||||
@@ -33,7 +38,7 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
|
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
|
||||||
const draft = chatId ? null : location.state;
|
const draft = chatId ? null : location.state;
|
||||||
const [startingChat, setStartingChat] = useState(false);
|
const [startingChat, setStartingChat] = useState(false);
|
||||||
const { fetchMessages, markAsRead, startChat } = useChats();
|
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, refreshAttachmentUrl } = useChats();
|
||||||
const { clearChatUnread } = useUnread();
|
const { clearChatUnread } = useUnread();
|
||||||
const { user, isAuthenticated } = useAuthContext();
|
const { user, isAuthenticated } = useAuthContext();
|
||||||
const [messages, setMessages] = useState([]);
|
const [messages, setMessages] = useState([]);
|
||||||
@@ -41,6 +46,13 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
const [loadError, setLoadError] = useState("");
|
const [loadError, setLoadError] = useState("");
|
||||||
const [sendError, setSendError] = useState("");
|
const [sendError, setSendError] = useState("");
|
||||||
const [showPost, setShowPost] = useState(false);
|
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 messagesEndRef = useRef(null);
|
||||||
const pageRef = useRef(null);
|
const pageRef = useRef(null);
|
||||||
|
|
||||||
@@ -107,9 +119,17 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
const header = page?.querySelector(".chat-header");
|
const header = page?.querySelector(".chat-header");
|
||||||
const inputArea = page?.querySelector(".chat-input-area");
|
const inputArea = page?.querySelector(".chat-input-area");
|
||||||
if (!header || !inputArea) return;
|
if (!header || !inputArea) return;
|
||||||
|
const list = page.querySelector(".chat-messages");
|
||||||
|
let inputHeight = inputArea.offsetHeight;
|
||||||
const update = () => {
|
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-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();
|
update();
|
||||||
const ro = new ResizeObserver(update);
|
const ro = new ResizeObserver(update);
|
||||||
@@ -125,6 +145,25 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
const handleSend = useCallback((e) => {
|
const handleSend = useCallback((e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const trimmed = input.trim();
|
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 (!trimmed) return;
|
||||||
|
|
||||||
if (draft) {
|
if (draft) {
|
||||||
@@ -149,7 +188,31 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
}
|
}
|
||||||
setInput("");
|
setInput("");
|
||||||
onActivity?.();
|
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 post = draft ? draft.post : getPostForChat(chatId);
|
||||||
const postImg = getImageUrl(post?.images?.[0]);
|
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>
|
<div className="chat-empty">{t('chat.noMessages')}</div>
|
||||||
)}
|
)}
|
||||||
{messages.map((m) => (
|
{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 ref={messagesEndRef} />
|
||||||
</div>
|
</div>
|
||||||
@@ -198,9 +267,25 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
|
|||||||
onSend={handleSend}
|
onSend={handleSend}
|
||||||
connected={draft ? !startingChat : connected}
|
connected={draft ? !startingChat : connected}
|
||||||
placeholder={t('chat.messagePlaceholder')}
|
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>
|
</div>
|
||||||
|
|
||||||
|
{viewer && (
|
||||||
|
<ChatPhotoViewer photos={viewer.photos} startIndex={viewer.index} onClose={() => setViewer(null)} />
|
||||||
|
)}
|
||||||
|
|
||||||
{showPost && (
|
{showPost && (
|
||||||
<PostDetailModal
|
<PostDetailModal
|
||||||
postId={postId}
|
postId={postId}
|
||||||
|
|||||||
@@ -351,6 +351,138 @@ button.chat-header-post:hover .chat-header-title { text-decoration: underline; }
|
|||||||
margin-bottom: 14px;
|
margin-bottom: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Фото в сообщениях ── */
|
||||||
|
.chat-bubble.has-photos {
|
||||||
|
padding: 4px;
|
||||||
|
width: min(300px, 70%);
|
||||||
|
}
|
||||||
|
.chat-bubble.has-photos .chat-bubble-text { padding: 6px 10px 0; }
|
||||||
|
.chat-bubble.has-photos .chat-bubble-time { padding: 0 8px 4px; }
|
||||||
|
.chat-photos {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: 3px;
|
||||||
|
border-radius: 14px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.chat-photos--single { grid-template-columns: 1fr; }
|
||||||
|
.chat-photo {
|
||||||
|
display: block;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
background: var(--bg-input);
|
||||||
|
aspect-ratio: 1;
|
||||||
|
cursor: zoom-in;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
/* Одно фото — в своих пропорциях (из width/height), но не выше экрана */
|
||||||
|
.chat-photos--single .chat-photo { aspect-ratio: 4 / 3; max-height: 60vh; }
|
||||||
|
.chat-photo img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Выбор фото перед отправкой ── */
|
||||||
|
.chat-attach-btn {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 44px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--bg-input);
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background .15s, color .15s;
|
||||||
|
}
|
||||||
|
.chat-attach-btn:hover:not(:disabled) { background: var(--hover-bg); color: var(--text-primary); }
|
||||||
|
.chat-attach-btn:disabled { opacity: .4; cursor: default; }
|
||||||
|
.chat-attach-strip {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 16px 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.chat-attach-thumb {
|
||||||
|
position: relative;
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 64px;
|
||||||
|
height: 64px;
|
||||||
|
border-radius: 12px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.chat-attach-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||||
|
.chat-attach-thumb.is-sending { opacity: .5; }
|
||||||
|
.chat-attach-thumb--busy { display: flex; align-items: center; justify-content: center; }
|
||||||
|
.chat-attach-remove {
|
||||||
|
position: absolute;
|
||||||
|
top: 3px;
|
||||||
|
right: 3px;
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: rgba(0, 0, 0, .6);
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.chat-attach-remove svg { width: 12px; height: 12px; }
|
||||||
|
.chat-attach-error { color: var(--err); font-size: .8rem; }
|
||||||
|
|
||||||
|
/* ── Просмотр фото ── */
|
||||||
|
.chat-viewer {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1000;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: rgba(0, 0, 0, .92);
|
||||||
|
}
|
||||||
|
.chat-viewer-img {
|
||||||
|
max-width: 100vw;
|
||||||
|
max-height: 100vh;
|
||||||
|
object-fit: contain;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.chat-viewer-close,
|
||||||
|
.chat-viewer-nav {
|
||||||
|
position: absolute;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: none;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: rgba(255, 255, 255, .14);
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.chat-viewer-close { top: calc(16px + env(safe-area-inset-top)); right: 16px; width: 40px; height: 40px; }
|
||||||
|
.chat-viewer-nav { top: 50%; transform: translateY(-50%); width: 44px; height: 44px; font-size: 1.8rem; line-height: 1; }
|
||||||
|
.chat-viewer-prev { left: 16px; }
|
||||||
|
.chat-viewer-next { right: 16px; }
|
||||||
|
.chat-viewer-close:hover,
|
||||||
|
.chat-viewer-nav:hover { background: rgba(255, 255, 255, .26); }
|
||||||
|
.chat-viewer-counter {
|
||||||
|
position: absolute;
|
||||||
|
bottom: calc(20px + env(safe-area-inset-bottom));
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
color: #fff;
|
||||||
|
font-size: .85rem;
|
||||||
|
opacity: .8;
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Chat List ── */
|
/* ── Chat List ── */
|
||||||
.chat-list {
|
.chat-list {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -496,6 +628,8 @@ button.chat-header-post:hover .chat-header-title { text-decoration: underline; }
|
|||||||
.chat-bubble {
|
.chat-bubble {
|
||||||
max-width: 85%;
|
max-width: 85%;
|
||||||
}
|
}
|
||||||
|
.chat-bubble.has-photos { width: min(280px, 85%); }
|
||||||
|
.chat-attach-strip { padding: 8px 12px 0; }
|
||||||
.chat-list {
|
.chat-list {
|
||||||
padding: 6px 10px;
|
padding: 6px 10px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -998,6 +998,10 @@
|
|||||||
max-width: 820px; margin: 0 auto; width: 100%;
|
max-width: 820px; margin: 0 auto; width: 100%;
|
||||||
padding-left: 24px; padding-right: 24px;
|
padding-left: 24px; padding-right: 24px;
|
||||||
}
|
}
|
||||||
|
.fd-chats-main .chat-page--embedded .chat-attach-strip {
|
||||||
|
max-width: 820px; margin: 0 auto; width: 100%;
|
||||||
|
padding-left: 24px; padding-right: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
.fd-chats-placeholder {
|
.fd-chats-placeholder {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
|||||||
@@ -63,7 +63,9 @@ export function getChatDisplayInfo(chat, post, unreadMap, t) {
|
|||||||
const imgSrc = getImageUrl(post?.images?.[0]);
|
const imgSrc = getImageUrl(post?.images?.[0]);
|
||||||
const emoji = post?.emoji;
|
const emoji = post?.emoji;
|
||||||
const unreadCount = unreadMap[chat.id] ?? chat.unreadCount ?? chat.unreadMessages ?? 0;
|
const unreadCount = unreadMap[chat.id] ?? chat.unreadCount ?? chat.unreadMessages ?? 0;
|
||||||
const preview = getLastMessageText(chat) || t('chat.noMessages');
|
// У сообщения только с фото текста нет — в превью пишем «Фото»
|
||||||
|
const photoPreview = chat.lastMessageAttachments > 0 ? `📷 ${t('chat.photoPreview')}` : "";
|
||||||
|
const preview = getLastMessageText(chat) || photoPreview || t('chat.noMessages');
|
||||||
|
|
||||||
return { title, imgSrc, emoji, unreadCount, preview };
|
return { title, imgSrc, emoji, unreadCount, preview };
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user