forked from mtusi2026/mtusi2026lab4
237 lines
7.1 KiB
TypeScript
237 lines
7.1 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import {
|
||
ArrowLeft,
|
||
CheckCheck,
|
||
RefreshCcw,
|
||
Send,
|
||
ShieldCheck,
|
||
UsersRound,
|
||
} from "lucide-react";
|
||
import {
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
type FormEvent,
|
||
type KeyboardEvent,
|
||
} from "react";
|
||
|
||
import { api } from "../api/client";
|
||
import type { Chat, Message, User } from "../api/types";
|
||
import {
|
||
dayKey,
|
||
formatDay,
|
||
formatMemberCount,
|
||
formatMessageTime,
|
||
shortID,
|
||
} from "../lib/format";
|
||
import { createIdempotencyKey } from "../lib/idempotency";
|
||
import { Avatar } from "./Avatar";
|
||
|
||
type ChatViewProps = {
|
||
chat: Chat;
|
||
currentUser: User;
|
||
onBack: () => void;
|
||
};
|
||
|
||
type SendEnvelope = {
|
||
text: string;
|
||
idempotencyKey: string;
|
||
};
|
||
|
||
export function ChatView({ chat, currentUser, onBack }: ChatViewProps) {
|
||
const queryClient = useQueryClient();
|
||
const messagesEnd = useRef<HTMLDivElement>(null);
|
||
const [draft, setDraft] = useState("");
|
||
const [failedEnvelope, setFailedEnvelope] = useState<SendEnvelope | null>(null);
|
||
|
||
const messagesQuery = useQuery({
|
||
queryKey: ["messages", chat.id],
|
||
queryFn: () => api.messages(chat.id),
|
||
refetchInterval: 3_000,
|
||
staleTime: 1_000,
|
||
});
|
||
|
||
const messages = messagesQuery.data ?? [];
|
||
|
||
useEffect(() => {
|
||
messagesEnd.current?.scrollIntoView({
|
||
behavior: messages.length > 1 ? "smooth" : "auto",
|
||
block: "end",
|
||
});
|
||
}, [chat.id, messages.length]);
|
||
|
||
const mutation = useMutation({
|
||
mutationFn: (envelope: SendEnvelope) =>
|
||
api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey),
|
||
onSuccess: (message) => {
|
||
setFailedEnvelope(null);
|
||
queryClient.setQueryData<Message[]>(
|
||
["messages", chat.id],
|
||
(current = []) => {
|
||
if (current.some((item) => item.id === message.id)) {
|
||
return current;
|
||
}
|
||
return [...current, message];
|
||
},
|
||
);
|
||
},
|
||
onError: (_error, envelope) => {
|
||
setFailedEnvelope(envelope);
|
||
},
|
||
});
|
||
|
||
const groups = useMemo(() => {
|
||
const result: Array<{ key: string; label: string; messages: Message[] }> = [];
|
||
for (const message of messages) {
|
||
const key = dayKey(message.created_at);
|
||
const current = result.at(-1);
|
||
if (!current || current.key !== key) {
|
||
result.push({
|
||
key,
|
||
label: formatDay(message.created_at),
|
||
messages: [message],
|
||
});
|
||
} else {
|
||
current.messages.push(message);
|
||
}
|
||
}
|
||
return result;
|
||
}, [messages]);
|
||
|
||
function send(envelope: SendEnvelope) {
|
||
if (!mutation.isPending) {
|
||
mutation.mutate(envelope);
|
||
}
|
||
}
|
||
|
||
function submit(event: FormEvent<HTMLFormElement>) {
|
||
event.preventDefault();
|
||
const text = draft.trim();
|
||
if (!text || Array.from(text).length > 4_000) {
|
||
return;
|
||
}
|
||
const envelope = { text, idempotencyKey: createIdempotencyKey() };
|
||
setDraft("");
|
||
setFailedEnvelope(null);
|
||
send(envelope);
|
||
}
|
||
|
||
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
|
||
if (event.key === "Enter" && !event.shiftKey) {
|
||
event.preventDefault();
|
||
event.currentTarget.form?.requestSubmit();
|
||
}
|
||
}
|
||
|
||
return (
|
||
<section className="conversation">
|
||
<header className="conversation-header">
|
||
<button
|
||
aria-label="Назад к списку чатов"
|
||
className="mobile-back-button"
|
||
onClick={onBack}
|
||
type="button"
|
||
>
|
||
<ArrowLeft aria-hidden="true" />
|
||
</button>
|
||
<Avatar label={chat.title} seed={chat.id} size="small" />
|
||
<div className="conversation-header__title">
|
||
<strong>{chat.title}</strong>
|
||
<span>{formatMemberCount(chat.member_ids.length)}</span>
|
||
</div>
|
||
<div className="conversation-header__security">
|
||
<ShieldCheck aria-hidden="true" />
|
||
<span>сессия защищена</span>
|
||
</div>
|
||
</header>
|
||
|
||
<div className="message-canvas">
|
||
<div className="message-canvas__shade" />
|
||
<div className="message-stream" aria-live="polite">
|
||
{messagesQuery.isLoading && (
|
||
<div className="floating-state">
|
||
<span className="loading-line" />
|
||
Загружаем историю
|
||
</div>
|
||
)}
|
||
|
||
{messagesQuery.isError && (
|
||
<div className="floating-state floating-state--error">
|
||
<p>История временно недоступна</p>
|
||
<button onClick={() => messagesQuery.refetch()} type="button">
|
||
<RefreshCcw aria-hidden="true" /> Повторить
|
||
</button>
|
||
</div>
|
||
)}
|
||
|
||
{!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && (
|
||
<div className="floating-state">
|
||
<UsersRound aria-hidden="true" />
|
||
<p>Сообщений пока нет. Начните разговор.</p>
|
||
</div>
|
||
)}
|
||
|
||
{groups.map((group) => (
|
||
<div className="message-day" key={group.key}>
|
||
<div className="date-divider"><span>{group.label}</span></div>
|
||
{group.messages.map((message) => {
|
||
const own = message.sender_id === currentUser.id;
|
||
return (
|
||
<article
|
||
className={`message-bubble ${own ? "message-bubble--own" : ""}`}
|
||
key={message.id}
|
||
>
|
||
<span className="message-bubble__sender">
|
||
{own ? "Вы" : shortID(message.sender_id)}
|
||
</span>
|
||
<p>{message.text}</p>
|
||
<span className="message-bubble__meta">
|
||
{formatMessageTime(message.created_at)}
|
||
{own && <CheckCheck aria-label="Доставлено серверу" />}
|
||
</span>
|
||
</article>
|
||
);
|
||
})}
|
||
</div>
|
||
))}
|
||
<div ref={messagesEnd} />
|
||
</div>
|
||
</div>
|
||
|
||
<footer className="composer">
|
||
{failedEnvelope && (
|
||
<div className="send-error" role="alert">
|
||
<span>Отправка не подтверждена.</span>
|
||
<button onClick={() => send(failedEnvelope)} type="button">
|
||
Повторить с тем же ключом
|
||
</button>
|
||
</div>
|
||
)}
|
||
<form onSubmit={submit}>
|
||
<textarea
|
||
aria-label="Текст сообщения"
|
||
maxLength={4_000}
|
||
onChange={(event) => setDraft(event.target.value)}
|
||
onKeyDown={handleKeyDown}
|
||
placeholder="Сообщение…"
|
||
rows={1}
|
||
value={draft}
|
||
/>
|
||
<span className="composer__counter">
|
||
{draft.length > 3_600 ? `${Array.from(draft).length}/4000` : ""}
|
||
</span>
|
||
<button
|
||
aria-label="Отправить"
|
||
className="send-button"
|
||
disabled={!draft.trim() || mutation.isPending}
|
||
type="submit"
|
||
>
|
||
<Send aria-hidden="true" />
|
||
</button>
|
||
</form>
|
||
</footer>
|
||
</section>
|
||
);
|
||
}
|