на оценку 5

This commit is contained in:
2026-11-10 16:21:46 +03:00
parent 276dbdad8a
commit 7110afc598
170 changed files with 21149 additions and 30 deletions
+26
View File
@@ -0,0 +1,26 @@
import { initials } from "../lib/format";
type AvatarProps = {
label: string;
seed?: string;
size?: "small" | "medium" | "large";
};
function tone(seed: string): number {
let hash = 0;
for (const character of seed) {
hash = (hash * 31 + character.codePointAt(0)!) >>> 0;
}
return hash % 5;
}
export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) {
return (
<span
aria-hidden="true"
className={`avatar avatar--${size} avatar--tone-${tone(seed)}`}
>
{initials(label)}
</span>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { Chat, User } from "../api/types";
import { formatMemberCount } from "../lib/format";
import { Avatar } from "./Avatar";
type ChatListProps = {
chats: Chat[];
currentUser: User;
error: boolean;
isLoading: boolean;
selectedChatID?: string;
onCreateChat: () => void;
};
export function ChatList({
chats,
currentUser,
error,
isLoading,
selectedChatID,
onCreateChat,
}: ChatListProps) {
const navigate = useNavigate();
const [search, setSearch] = useState("");
const filteredChats = useMemo(() => {
const normalized = search.trim().toLocaleLowerCase("ru");
if (!normalized) {
return chats;
}
return chats.filter((chat) =>
chat.title.toLocaleLowerCase("ru").includes(normalized),
);
}, [chats, search]);
return (
<aside className="chat-sidebar">
<header className="chat-sidebar__header">
<div>
<p className="eyebrow">Сообщения</p>
<h1>Чаты</h1>
</div>
<button
aria-label="Создать чат"
className="soft-icon-button"
onClick={onCreateChat}
type="button"
>
<MessageSquarePlus aria-hidden="true" />
</button>
</header>
<div className="search-box">
<Search aria-hidden="true" />
<input
aria-label="Поиск чатов"
onChange={(event) => setSearch(event.target.value)}
placeholder="Поиск"
value={search}
/>
{search && (
<button aria-label="Очистить поиск" onClick={() => setSearch("")} type="button">
<X aria-hidden="true" />
</button>
)}
</div>
<div className="chat-list" aria-live="polite">
{isLoading && (
<div className="sidebar-state">
<span className="loading-line" />
<p>Загружаем чаты…</p>
</div>
)}
{error && (
<div className="sidebar-state sidebar-state--error">
<p>Не удалось загрузить список чатов.</p>
</div>
)}
{!isLoading && !error && filteredChats.length === 0 && (
<div className="sidebar-state">
<UsersRound aria-hidden="true" />
<p>{search ? "Ничего не найдено" : "У вас пока нет чатов"}</p>
{!search && (
<button className="text-button" onClick={onCreateChat} type="button">
Создать первый
</button>
)}
</div>
)}
{filteredChats.map((chat) => (
<button
className={`chat-row ${selectedChatID === chat.id ? "chat-row--active" : ""}`}
key={chat.id}
onClick={() => navigate(`/app/chats/${chat.id}`)}
type="button"
>
<Avatar label={chat.title} seed={chat.id} />
<span className="chat-row__body">
<strong>{chat.title}</strong>
<small>{formatMemberCount(chat.member_ids.length)}</small>
</span>
{chat.member_ids.includes(currentUser.id) && (
<span className="chat-row__status" title="Вы участник">
•
</span>
)}
</button>
))}
</div>
<footer className="sidebar-footer">
<span className="status-dot" />
API подключён
</footer>
</aside>
);
}
+236
View File
@@ -0,0 +1,236 @@
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>
);
}
@@ -0,0 +1,148 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, UserRoundPlus, X } from "lucide-react";
import { useEffect, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { api, ApiError } from "../api/client";
import type { Chat, User } from "../api/types";
import { shortID } from "../lib/format";
type CreateChatDialogProps = {
currentUser: User;
onClose: () => void;
};
const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function CreateChatDialog({
currentUser,
onClose,
}: CreateChatDialogProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [title, setTitle] = useState("");
const [memberInput, setMemberInput] = useState("");
const [validationError, setValidationError] = useState("");
useEffect(() => {
function closeOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [onClose]);
const mutation = useMutation({
mutationFn: api.createChat,
onSuccess: (chat) => {
queryClient.setQueryData<Chat[]>(["chats"], (current = []) => [
...current,
chat,
]);
onClose();
navigate(`/app/chats/${chat.id}`);
},
});
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setValidationError("");
const enteredIDs = memberInput
.split(/[\s,;]+/)
.map((value) => value.trim())
.filter(Boolean);
const memberIds = Array.from(new Set([currentUser.id, ...enteredIDs]));
if (!title.trim() || Array.from(title.trim()).length > 100) {
setValidationError("Название должно содержать от 1 до 100 символов");
return;
}
const invalidID = enteredIDs.find((id) => !uuidPattern.test(id));
if (invalidID) {
setValidationError(`Некорректный UUID: ${invalidID}`);
return;
}
mutation.mutate({ title: title.trim(), memberIds });
}
const serverError =
mutation.error instanceof ApiError
? mutation.error.message
: mutation.error
? "Не удалось создать чат"
: "";
return (
<div className="dialog-backdrop" onMouseDown={onClose}>
<section
aria-labelledby="create-chat-title"
aria-modal="true"
className="dialog-card"
onMouseDown={(event) => event.stopPropagation()}
role="dialog"
>
<header className="dialog-card__header">
<div>
<p className="eyebrow">Новый разговор</p>
<h2 id="create-chat-title">Создать чат</h2>
</div>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={onClose}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<form className="dialog-form" onSubmit={submit}>
<label>
<span>Название</span>
<div className="input-shell">
<Plus aria-hidden="true" />
<input
autoFocus
maxLength={100}
onChange={(event) => setTitle(event.target.value)}
placeholder="Например, Команда проекта"
required
value={title}
/>
</div>
</label>
<label>
<span>UUID участников</span>
<div className="textarea-shell">
<UserRoundPlus aria-hidden="true" />
<textarea
onChange={(event) => setMemberInput(event.target.value)}
placeholder="Вставьте UUID через пробел, запятую или с новой строки"
rows={4}
value={memberInput}
/>
</div>
<small>
Ваш ID добавлен автоматически: <code>{shortID(currentUser.id)}</code>
</small>
</label>
{(validationError || serverError) && (
<div className="form-error" role="alert">
{validationError || serverError}
</div>
)}
<button className="primary-button" disabled={mutation.isPending} type="submit">
{mutation.isPending ? "Создаём…" : "Создать чат"}
</button>
</form>
</section>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { MessageSquarePlus } from "lucide-react";
type EmptyChatProps = {
hasChats: boolean;
onCreateChat: () => void;
};
export function EmptyChat({ hasChats, onCreateChat }: EmptyChatProps) {
return (
<section className="conversation conversation--empty">
<div className="empty-chat-card">
<span className="empty-chat-card__line" />
<p className="eyebrow">MTUCI Messenger</p>
<h2>{hasChats ? "Выберите чат" : "Начните разговор"}</h2>
<p>
{hasChats
? "История и новые сообщения появятся здесь."
: "Создайте первый чат и пригласите участников по UUID."}
</p>
{!hasChats && (
<button className="primary-button" onClick={onCreateChat} type="button">
<MessageSquarePlus aria-hidden="true" />
Создать чат
</button>
)}
</div>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
export function LoadingScreen() {
return (
<main className="loading-screen" aria-live="polite">
<div className="brand-mark brand-mark--large" aria-hidden="true">
M
</div>
<p>Подключаемся к Messenger</p>
<span className="loading-line" />
</main>
);
}
@@ -0,0 +1,42 @@
import { MessagesSquare, UserRound } from "lucide-react";
import { Link } from "react-router-dom";
import type { User } from "../api/types";
import { Avatar } from "./Avatar";
type NavigationRailProps = {
user: User;
profileOpen: boolean;
};
export function NavigationRail({ user, profileOpen }: NavigationRailProps) {
return (
<nav className="navigation-rail" aria-label="Основная навигация">
<Link className="rail-brand" to="/app" aria-label="MTUCI Messenger">
M
</Link>
<div className="rail-actions">
<Link
className={`rail-action ${profileOpen ? "" : "rail-action--active"}`}
to="/app"
>
<MessagesSquare aria-hidden="true" />
<span>Чаты</span>
</Link>
<Link
className={`rail-action ${profileOpen ? "rail-action--active" : ""}`}
to="/app/profile"
>
<UserRound aria-hidden="true" />
<span>Профиль</span>
</Link>
</div>
<Link className="rail-profile" to="/app/profile" aria-label="Открыть профиль">
<Avatar label={user.display_name} seed={user.id} size="small" />
<span className="presence-dot" />
</Link>
</nav>
);
}
+123
View File
@@ -0,0 +1,123 @@
import {
CalendarDays,
Check,
Copy,
LogOut,
ShieldCheck,
UserRound,
X,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import type { User } from "../api/types";
import { useAuth } from "../auth/AuthProvider";
import { Avatar } from "./Avatar";
type ProfileDrawerProps = {
user: User;
};
const createdAtFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function ProfileDrawer({ user }: ProfileDrawerProps) {
const { logout } = useAuth();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const [error, setError] = useState("");
const [isLoggingOut, setIsLoggingOut] = useState(false);
async function copyID() {
await navigator.clipboard.writeText(user.id);
setCopied(true);
window.setTimeout(() => setCopied(false), 1800);
}
async function submitLogout() {
setError("");
setIsLoggingOut(true);
try {
await logout();
navigate("/login", { replace: true });
} catch {
setError("Не удалось завершить сессию. Попробуйте ещё раз.");
setIsLoggingOut(false);
}
}
return (
<>
<button
aria-label="Закрыть профиль"
className="drawer-backdrop"
onClick={() => navigate("/app")}
type="button"
/>
<aside className="profile-drawer" aria-label="Профиль пользователя">
<header className="profile-drawer__header">
<p className="eyebrow">Ваш аккаунт</p>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={() => navigate("/app")}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<div className="profile-identity">
<Avatar label={user.display_name} seed={user.id} size="large" />
<h2>{user.display_name}</h2>
<p>@{user.username}</p>
<span className="profile-badge">
<ShieldCheck aria-hidden="true" />
серверная сессия
</span>
</div>
<dl className="profile-details">
<div>
<dt><UserRound aria-hidden="true" /> ID аккаунта</dt>
<dd>
<code>{user.id}</code>
<button
aria-label="Скопировать ID"
className="copy-button"
onClick={copyID}
type="button"
>
{copied ? <Check /> : <Copy />}
</button>
</dd>
</div>
<div>
<dt><CalendarDays aria-hidden="true" /> Дата регистрации</dt>
<dd>{createdAtFormatter.format(new Date(user.created_at))}</dd>
</div>
</dl>
<div className="profile-roadmap">
<strong>Следующие версии</strong>
<p>Аватар, редактирование имени и смена пароля появятся после API-контрактов.</p>
</div>
{error && <div className="form-error" role="alert">{error}</div>}
<button
className="logout-button"
disabled={isLoggingOut}
onClick={submitLogout}
type="button"
>
<LogOut aria-hidden="true" />
{isLoggingOut ? "Завершаем…" : "Выйти из аккаунта"}
</button>
</aside>
</>
);
}