704 lines
34 KiB
JavaScript
704 lines
34 KiB
JavaScript
import { attachmentSession } from '/attachments.js';
|
||
import { recordRequest, updateSessionInfo, updateHistoryInfo } from "/diagnostics.js";
|
||
|
||
import { setMascotMood, celebrateMascots } from "/mascots.js";
|
||
import { MessageView } from "/message-view.js";
|
||
import { paintAvatar } from "/avatars.js";
|
||
import { startClusterView } from '/cluster-view.js';
|
||
|
||
const $ = id => document.getElementById(id);
|
||
const storageKey = "n1k0der.session";
|
||
const messageView = new MessageView($("message-list"));
|
||
const state = { session: null, chats: [], chatsStatus: "loading", chatsCursor: null, current: null, messages: new Map(),
|
||
serverIds: new Set(), members: new Map(), olderCursor: null, historyReady: false, epoch: 0, syncing: false, sending: false, drafts: new Map() };
|
||
let toastTimer, unseenMessages = 0;
|
||
const pendingMessages = new Map();
|
||
const attachedDrafts = new Map();
|
||
let uploadBusy = false;
|
||
const chatRows = new Map();
|
||
let chatsLoading = false, lastChatRefresh = 0;
|
||
const reactions = new Map(), reactionBusy = new Set();
|
||
let reactionVersion = 0;
|
||
|
||
class ApiError extends Error {
|
||
constructor(message, status = 0) { super(message); this.status = status; }
|
||
}
|
||
|
||
function notice(id, message, success = false) {
|
||
const element = $(id);
|
||
element.textContent = message;
|
||
element.hidden = !message;
|
||
element.classList.toggle("success", success);
|
||
}
|
||
|
||
function toast(message, error = false) {
|
||
clearTimeout(toastTimer);
|
||
$("toast").textContent = message;
|
||
$("toast").classList.toggle("error", error);
|
||
$("toast").hidden = false;
|
||
toastTimer = setTimeout(() => { $("toast").hidden = true; }, error ? 6500 : 3000);
|
||
}
|
||
|
||
async function request(path, { method = "GET", body, headers = {}, auth = true, background = false, raw } = {}) {
|
||
const started = performance.now();
|
||
let httpStatus = null, requestId = null, instanceId = null, outcome = "network";
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), raw ? 90000 : 12000);
|
||
// Authorization is explicit; disable the browser's implicit Basic-auth handling.
|
||
const options = { method, headers: { Accept: "application/json", ...headers }, signal: controller.signal, cache: "no-store", credentials: "omit" };
|
||
if (auth && state.session) options.headers.Authorization = "Bearer " + state.session.token;
|
||
if (body !== undefined) {
|
||
options.body = JSON.stringify(body);
|
||
options.headers["Content-Type"] = "application/json";
|
||
}
|
||
if (raw !== undefined) options.body = raw;
|
||
try {
|
||
const response = await fetch(path, options);
|
||
httpStatus = response.status;
|
||
requestId = response.headers.get("X-Request-Id");
|
||
instanceId = response.headers.get("X-Instance-Id");
|
||
outcome = "unreadable";
|
||
const data = response.status === 204 ? null : await response.json();
|
||
outcome = response.ok ? "success" : "http_error";
|
||
if (!response.ok) {
|
||
if (response.status === 401 && auth) endSession("Сессия закончилась. Войдите снова.");
|
||
throw new ApiError(data?.error?.message || "Не удалось выполнить запрос.", response.status);
|
||
}
|
||
return data;
|
||
} catch (error) {
|
||
if (error instanceof ApiError) throw error;
|
||
throw new ApiError("Нет ответа от сервера. Проверьте соединение и попробуйте позже.");
|
||
} finally {
|
||
clearTimeout(timer);
|
||
recordRequest({ method, path, status: httpStatus, requestId, instanceId, outcome, background,
|
||
durationMs: Math.round(performance.now() - started),
|
||
authorization: options.headers.Authorization?.split(" ")[0] || "Без авторизации" });
|
||
}
|
||
}
|
||
|
||
function basic(username, password) {
|
||
const bytes = new TextEncoder().encode(username + ":" + password);
|
||
return "Basic " + btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join(""));
|
||
}
|
||
|
||
function selectAuthTab(register) {
|
||
$("register-panel").hidden = !register;
|
||
$("login-panel").hidden = register;
|
||
$("tab-register").classList.toggle("active", register);
|
||
$("tab-login").classList.toggle("active", !register);
|
||
$("tab-register").setAttribute("aria-pressed", String(register));
|
||
$("tab-login").setAttribute("aria-pressed", String(!register));
|
||
notice("auth-notice", "");
|
||
}
|
||
|
||
function setFormBusy(form, busy) {
|
||
form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; });
|
||
}
|
||
|
||
function persistSession(session) {
|
||
try { sessionStorage.setItem(storageKey, JSON.stringify(session)); } catch { /* session still works in memory */ }
|
||
}
|
||
|
||
async function enterSession(session) {
|
||
reactions.clear(); reactionBusy.clear(); reactionVersion++;
|
||
state.epoch++;
|
||
state.session = session;
|
||
attachmentSession(session.token);
|
||
clearAttachedDrafts();
|
||
updateSessionInfo({ name: session.user.display_name, expiresAt: session.expires_at });
|
||
updateHistoryInfo(null);
|
||
state.current = null;
|
||
state.messages.clear();
|
||
state.serverIds.clear();
|
||
state.chats = [];
|
||
chatRows.clear();
|
||
state.chatsStatus = "loading";
|
||
state.chatsCursor = null;
|
||
state.drafts.clear();
|
||
state.syncing = false;
|
||
state.sending = false;
|
||
persistSession(session);
|
||
$("auth-screen").hidden = true;
|
||
$("app-screen").hidden = false;
|
||
$("app-screen").classList.remove("chat-open");
|
||
$("welcome").hidden = false;
|
||
$("workspace-error").hidden = true;
|
||
$("conversation-error").hidden = true;
|
||
$("conversation").hidden = true;
|
||
$("profile-name").textContent = session.user.display_name;
|
||
$("profile-username").textContent = "@" + session.user.username;
|
||
paintAvatar($("profile-avatar"), session.user.id, session.user.display_name);
|
||
$("chat-search").value = "";
|
||
renderChats();
|
||
try { await loadChats(false, true); } catch (error) {
|
||
if (state.session?.token === session.token) { $("welcome").hidden = true; $("workspace-error").hidden = false; }
|
||
}
|
||
}
|
||
|
||
function endSession(message = "") {
|
||
reactions.clear(); reactionBusy.clear(); reactionVersion++;
|
||
state.epoch++;
|
||
state.session = null;
|
||
attachmentSession(null);
|
||
clearAttachedDrafts();
|
||
updateSessionInfo(null);
|
||
updateHistoryInfo(null);
|
||
state.current = null;
|
||
state.chats = [];
|
||
chatRows.clear();
|
||
state.messages.clear();
|
||
state.serverIds.clear();
|
||
state.drafts.clear();
|
||
pendingMessages.clear();
|
||
try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ }
|
||
document.querySelectorAll("dialog[open]").forEach(dialog => dialog.close());
|
||
messageView.clear();
|
||
unseenMessages = 0;
|
||
updateJumpButton();
|
||
$("chat-list").replaceChildren();
|
||
$("message-input").value = "";
|
||
$("app-screen").hidden = true;
|
||
$("auth-screen").hidden = false;
|
||
$("login-password").value = "";
|
||
selectAuthTab(false);
|
||
notice("auth-notice", message);
|
||
}
|
||
|
||
$("tab-login").addEventListener("click", () => selectAuthTab(false));
|
||
$("tab-register").addEventListener("click", () => selectAuthTab(true));
|
||
|
||
$("login-form").addEventListener("submit", async event => {
|
||
event.preventDefault();
|
||
const form = event.currentTarget;
|
||
const username = $("login-username").value.trim();
|
||
const password = $("login-password").value;
|
||
setFormBusy(form, true);
|
||
setMascotMood("pending");
|
||
notice("auth-notice", "");
|
||
try {
|
||
const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } });
|
||
form.reset();
|
||
await celebrateMascots();
|
||
await enterSession(session);
|
||
} catch (error) { setMascotMood("error"); notice("auth-notice", error.status === 401 ? "Неверный логин или пароль." : error.message); }
|
||
finally { setFormBusy(form, false); }
|
||
});
|
||
|
||
$("register-form").addEventListener("submit", async event => {
|
||
event.preventDefault();
|
||
const form = event.currentTarget;
|
||
const username = $("register-username").value.trim();
|
||
const displayName = $("register-name").value.trim();
|
||
const password = $("register-password").value;
|
||
if (Array.from(displayName).length > 100) return notice("auth-notice", "Имя должно содержать от 1 до 100 символов.");
|
||
if (Array.from(password).length < 12 || Array.from(password).length > 128 || !password.trim()) {
|
||
setMascotMood("short");
|
||
return notice("auth-notice", "Пароль должен содержать от 12 до 128 символов.");
|
||
}
|
||
setFormBusy(form, true);
|
||
setMascotMood("pending");
|
||
notice("auth-notice", "");
|
||
let registered = false;
|
||
try {
|
||
await request("/api/v1/users", { method: "POST", auth: false, body: { username, display_name: displayName, password } });
|
||
registered = true;
|
||
const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } });
|
||
form.reset();
|
||
await celebrateMascots();
|
||
await enterSession(session);
|
||
toast("Добро пожаловать, " + session.user.display_name + "!");
|
||
} catch (error) {
|
||
setMascotMood("error");
|
||
if (registered) {
|
||
form.reset();
|
||
selectAuthTab(false);
|
||
$("login-username").value = username;
|
||
notice("auth-notice", "Аккаунт создан. Войдите, когда сервер будет доступен.");
|
||
} else notice("auth-notice", error.status === 409 ? "Это имя пользователя уже занято. Выберите другое." : error.message);
|
||
} finally { setFormBusy(form, false); }
|
||
});
|
||
|
||
function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); }
|
||
function chatActivity(chat) { return chat.last_message?.created_at || chat.created_at; }
|
||
function chatTime(value) {
|
||
const date = new Date(value), now = new Date();
|
||
return date.toDateString() === now.toDateString()
|
||
? date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })
|
||
: date.toLocaleDateString("ru-RU", { day: "numeric", month: "short" });
|
||
}
|
||
|
||
async function loadChats(more = false, background = false) {
|
||
if (chatsLoading) return;
|
||
chatsLoading = true;
|
||
const token = state.session?.token;
|
||
const cursor = more ? state.chatsCursor : null;
|
||
$("chat-list").setAttribute("aria-busy", "true");
|
||
$("refresh-chats").classList.add("is-loading");
|
||
try {
|
||
const data = await request("/api/ui/chats?limit=100" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : ""), { background });
|
||
if (token !== state.session?.token) return;
|
||
const previous = new Map(state.chats.map(chat => [chat.id, chat]));
|
||
const incoming = data.items.map(chat => {
|
||
const existing = previous.get(chat.id)?.last_message;
|
||
return existing && (!chat.last_message || compareMessages(existing, chat.last_message) > 0)
|
||
? { ...chat, last_message: existing } : chat;
|
||
});
|
||
state.chats = more ? [...state.chats, ...incoming.filter(chat => !previous.has(chat.id))] : incoming;
|
||
state.chatsCursor = data.next_cursor;
|
||
state.chatsStatus = "ready";
|
||
lastChatRefresh = Date.now();
|
||
$("workspace-error").hidden = true;
|
||
if (!state.current) $("welcome").hidden = false;
|
||
renderChats();
|
||
} catch (error) {
|
||
if (token === state.session?.token && !state.chats.length) {
|
||
state.chatsStatus = "error"; renderChats();
|
||
}
|
||
throw error;
|
||
} finally {
|
||
chatsLoading = false;
|
||
$("chat-list").setAttribute("aria-busy", "false");
|
||
$("refresh-chats").classList.remove("is-loading");
|
||
}
|
||
}
|
||
|
||
function renderChats() {
|
||
const query = $("chat-search").value.trim().toLocaleLowerCase("ru-RU");
|
||
const chats = [...state.chats].sort((a, b) => chatActivity(b).localeCompare(chatActivity(a)) || b.id.localeCompare(a.id))
|
||
.filter(chat => chat.title.toLocaleLowerCase("ru-RU").includes(query));
|
||
$("chat-count").textContent = state.chats.length || "";
|
||
$("more-chats").hidden = !state.chatsCursor;
|
||
const nodes = chats.map(chat => {
|
||
let row = chatRows.get(chat.id);
|
||
if (!row) {
|
||
const button = document.createElement("button"); button.className = "chat-row";
|
||
button.dataset.chatId = chat.id;
|
||
const avatar = document.createElement("span"); avatar.className = "avatar";
|
||
const description = document.createElement("span"); description.className = "chat-row-text";
|
||
const heading = document.createElement("span"); heading.className = "chat-row-heading";
|
||
const title = document.createElement("strong"), time = document.createElement("time");
|
||
const preview = document.createElement("small"); preview.className = "chat-preview";
|
||
heading.append(title, time); description.append(heading, preview); button.append(avatar, description);
|
||
button.addEventListener("click", () => {
|
||
const current = state.chats.find(item => item.id === chat.id);
|
||
if (current) void selectChat(current);
|
||
});
|
||
row = { button, avatar, title, time, preview }; chatRows.set(chat.id, row);
|
||
}
|
||
row.button.classList.toggle("active", chat.id === state.current?.id);
|
||
row.button.setAttribute("aria-pressed", String(chat.id === state.current?.id));
|
||
paintAvatar(row.avatar, chat.id, chat.title);
|
||
row.title.textContent = chat.title;
|
||
row.time.dateTime = chatActivity(chat); row.time.textContent = chatTime(chatActivity(chat));
|
||
row.time.title = new Date(chatActivity(chat)).toLocaleString("ru-RU");
|
||
const message = chat.last_message;
|
||
row.preview.textContent = message
|
||
? (message.sender_id === state.session?.user.id ? "Вы: " : "") + (message.text.replace(/\s+/gu, " ").trim() || "Изображение")
|
||
: "Пока без сообщений · " + memberCount(chat.member_ids.length);
|
||
return row.button;
|
||
});
|
||
if (!nodes.length) {
|
||
const empty = document.createElement("p"); empty.className = "list-empty";
|
||
empty.textContent = state.chatsStatus === "loading" ? "Загружаем чаты…" : state.chatsStatus === "error" ? "Не удалось загрузить чаты." : query ? "Чаты не найдены." : "Пока нет чатов.";
|
||
nodes.push(empty);
|
||
}
|
||
const list = $("chat-list"), wanted = new Set(nodes);
|
||
for (const node of [...list.children]) if (!wanted.has(node)) node.remove();
|
||
let next = list.firstChild;
|
||
for (const node of nodes) {
|
||
if (node === next) next = next.nextSibling;
|
||
else list.insertBefore(node, next);
|
||
}
|
||
}
|
||
|
||
function updateChatPreview(chatId, items) {
|
||
const chat = state.chats.find(item => item.id === chatId);
|
||
const last = items.reduce((latest, message) => !latest || compareMessages(message, latest) > 0 ? message : latest, null);
|
||
if (chat && last && (!chat.last_message || compareMessages(last, chat.last_message) > 0)) {
|
||
chat.last_message = last; renderChats();
|
||
}
|
||
}
|
||
|
||
$("retry-chats").addEventListener("click", async () => {
|
||
const button = $("retry-chats"); button.disabled = true;
|
||
try { await loadChats(); } catch (error) { toast(error.message, true); }
|
||
finally { button.disabled = false; }
|
||
});
|
||
$("retry-messages").addEventListener("click", async () => {
|
||
const button = $("retry-messages"); button.disabled = true;
|
||
try { await syncRecent(true); } catch (error) { toast(error.message, true); }
|
||
finally { button.disabled = false; }
|
||
});
|
||
|
||
$("chat-search").addEventListener("input", renderChats);
|
||
$("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } });
|
||
$("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } });
|
||
|
||
async function selectChat(chat) {
|
||
if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; }
|
||
if (state.current) state.drafts.set(state.current.id, $("message-input").value);
|
||
state.epoch++;
|
||
reactions.clear(); reactionBusy.clear(); reactionVersion++;
|
||
state.current = chat;
|
||
state.members = new Map([[state.session.user.id, state.session.user]]);
|
||
renderChats();
|
||
state.messages = new Map();
|
||
state.serverIds = new Set();
|
||
state.olderCursor = null;
|
||
state.historyReady = false;
|
||
updateHistoryInfo({ title: chat.title, loaded: 0, hasOlder: false, ready: false });
|
||
state.syncing = false;
|
||
$("current-title").textContent = chat.title;
|
||
$("current-members").textContent = memberCount(chat.member_ids.length);
|
||
paintAvatar($("current-avatar"), chat.id, chat.title);
|
||
$("welcome").hidden = true;
|
||
$("workspace-error").hidden = true;
|
||
$("conversation-error").hidden = true;
|
||
$("conversation").hidden = false;
|
||
$("app-screen").classList.add("chat-open");
|
||
$("message-input").value = state.drafts.get(chat.id) || "";
|
||
renderAttachedDrafts();
|
||
updateComposer();
|
||
messageView.clear();
|
||
unseenMessages = 0;
|
||
updateJumpButton();
|
||
$("empty-conversation").hidden = true;
|
||
$("older-messages").hidden = true;
|
||
$("messages-loading").hidden = false;
|
||
$("message-list").setAttribute("aria-busy", "true");
|
||
if (!matchMedia("(prefers-reduced-motion: reduce)").matches) $("conversation").animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 180, easing: "ease-out" });
|
||
try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); }
|
||
catch (error) { if (state.historyReady) toast(error.message, true); }
|
||
}
|
||
|
||
async function loadMembers(epoch, chatId) {
|
||
const data = await request(`/api/ui/chats/${chatId}/members`, { background: true });
|
||
if (epoch !== state.epoch) return;
|
||
state.members = new Map(data.items.map(user => [user.id, user]));
|
||
if (state.historyReady) renderMessages();
|
||
}
|
||
|
||
function mergeMessages(items) {
|
||
let changed = false;
|
||
for (const item of items) {
|
||
const previous = state.messages.get(item.id);
|
||
if (!previous || previous.text !== item.text || previous.sender_id !== item.sender_id || previous.created_at !== item.created_at) {
|
||
state.messages.set(item.id, item);
|
||
changed = true;
|
||
}
|
||
state.serverIds.add(item.id);
|
||
}
|
||
return changed;
|
||
}
|
||
|
||
function compareMessages(a, b) {
|
||
return a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id);
|
||
}
|
||
|
||
async function syncRecent(initial = false, background = false) {
|
||
if (!state.current || !state.session || state.syncing) return;
|
||
const epoch = state.epoch, chatId = state.current.id;
|
||
state.syncing = true;
|
||
try {
|
||
const page = await request(`/api/ui/chats/${chatId}/messages?limit=50`, { background });
|
||
if (epoch !== state.epoch) return;
|
||
$("conversation-error").hidden = true;
|
||
const wasReady = state.historyReady, oldCursor = state.olderCursor;
|
||
const latest = [...state.messages.values()].reduce((last, item) => !last || compareMessages(item, last) > 0 ? item : last, null);
|
||
const incoming = initial || !latest ? 0 : page.items.filter(item => !state.messages.has(item.id) && compareMessages(item, latest) > 0).length;
|
||
const overlap = page.items.some(item => state.serverIds.has(item.id));
|
||
state.historyReady = true;
|
||
// On a large burst, the older button pages through the newly discovered gap.
|
||
if (initial || (!overlap && page.items.length === 50)) state.olderCursor = page.next_cursor;
|
||
updateChatPreview(chatId, page.items);
|
||
const changed = mergeMessages(page.items);
|
||
if (initial || changed || !wasReady || oldCursor !== state.olderCursor) {
|
||
renderMessages(initial ? "bottom" : "preserve", incoming);
|
||
}
|
||
const visible = [...document.querySelectorAll('article.message')].filter(node => {
|
||
const rect = node.getBoundingClientRect(), region = $('message-scroll').getBoundingClientRect();
|
||
return rect.bottom >= region.top && rect.top <= region.bottom;
|
||
}).map(node => node.dataset.messageId);
|
||
await refreshReactions([...new Set([...visible, ...page.items.map(item => item.id)])].slice(0,100));
|
||
} catch (error) {
|
||
if (epoch === state.epoch && state.session && !state.historyReady) {
|
||
$("empty-conversation").hidden = true;
|
||
$("conversation-error").hidden = false;
|
||
}
|
||
throw error;
|
||
} finally { if (epoch === state.epoch) {
|
||
state.syncing = false;
|
||
$("messages-loading").hidden = true;
|
||
$("message-list").setAttribute("aria-busy", "false");
|
||
} }
|
||
}
|
||
|
||
$("older-messages").addEventListener("click", async () => {
|
||
if (!state.olderCursor || !state.current) return;
|
||
const epoch = state.epoch;
|
||
$("older-messages").disabled = true;
|
||
try {
|
||
const page = await request(`/api/ui/chats/${state.current.id}/messages?limit=50&cursor=${encodeURIComponent(state.olderCursor)}`);
|
||
if (epoch !== state.epoch) return;
|
||
mergeMessages(page.items);
|
||
state.olderCursor = page.next_cursor;
|
||
renderMessages("prepend");
|
||
await refreshReactions(page.items.map(item => item.id));
|
||
} catch (error) { toast(error.message, true); }
|
||
finally { $("older-messages").disabled = false; }
|
||
});
|
||
|
||
function renderMessages(mode = "preserve", incoming = 0) {
|
||
const scroll = $("message-scroll"), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop;
|
||
const atBottom = oldHeight - oldTop - scroll.clientHeight < 85;
|
||
const messages = [...state.messages.values()].sort(compareMessages);
|
||
messageView.render(messages, state.session?.user.id, state.members, mode === "bottom" || incoming > 0);
|
||
messageView.renderReactions(reactions, reactionBusy);
|
||
$("empty-conversation").hidden = !state.historyReady || messages.length !== 0;
|
||
$("older-messages").hidden = !state.olderCursor;
|
||
updateHistoryInfo({ title: state.current?.title, loaded: messages.length, hasOlder: Boolean(state.olderCursor), ready: state.historyReady });
|
||
if (mode === "bottom" || (mode === "preserve" && atBottom)) {
|
||
scroll.scrollTop = scroll.scrollHeight;
|
||
unseenMessages = 0;
|
||
} else if (mode === "prepend") scroll.scrollTop = oldTop + scroll.scrollHeight - oldHeight;
|
||
else {
|
||
scroll.scrollTop = oldTop;
|
||
unseenMessages += incoming;
|
||
}
|
||
updateJumpButton();
|
||
}
|
||
|
||
async function refreshReactions(ids) {
|
||
if (!ids.length || !state.current) return;
|
||
const epoch = state.epoch, version = reactionVersion, chatId = state.current.id;
|
||
try {
|
||
const data = await request(`/api/ui/chats/${chatId}/reactions?message_ids=${ids.join(',')}`, {background:true});
|
||
if (epoch !== state.epoch || version !== reactionVersion) return;
|
||
const scroll = $('message-scroll'), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop;
|
||
const atBottom = oldHeight - oldTop - scroll.clientHeight < 85;
|
||
for (const id of ids) reactions.set(id, data.items.filter(item => item.message_id === id));
|
||
messageView.renderReactions(reactions, reactionBusy);
|
||
scroll.scrollTop = atBottom ? scroll.scrollHeight : oldTop;
|
||
} catch { /* Message history remains usable; reaction changes show their own error. */ }
|
||
}
|
||
|
||
$('message-list').addEventListener('reactionchange', async event => {
|
||
const {messageId, reaction, present} = event.detail;
|
||
if (!state.current || reactionBusy.has(messageId)) return;
|
||
const epoch = state.epoch, chatId = state.current.id;
|
||
reactionVersion++; reactionBusy.add(messageId); messageView.renderReactions(reactions, reactionBusy);
|
||
try {
|
||
await request(`/api/ui/chats/${chatId}/messages/${messageId}/reactions/${reaction}`, {method:present ? 'PUT' : 'DELETE'});
|
||
if (epoch !== state.epoch) return;
|
||
reactionVersion++;
|
||
await refreshReactions([messageId]);
|
||
} catch (error) { if (epoch === state.epoch) toast('Не удалось изменить реакцию. ' + error.message, true); }
|
||
finally { if (epoch === state.epoch) { reactionBusy.delete(messageId); messageView.renderReactions(reactions, reactionBusy); } }
|
||
});
|
||
|
||
function updateJumpButton() {
|
||
const scroll = $("message-scroll"), button = $("jump-latest");
|
||
const atBottom = scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight < 85;
|
||
if (atBottom) unseenMessages = 0;
|
||
button.hidden = atBottom || state.messages.size === 0;
|
||
const label = unseenMessages ? `Новые сообщения: ${unseenMessages} ↓` : "К последним ↓";
|
||
if (button.textContent !== label) button.textContent = label;
|
||
}
|
||
|
||
$("message-scroll").addEventListener("scroll", updateJumpButton, { passive: true });
|
||
$("jump-latest").addEventListener("click", () => {
|
||
const scroll = $("message-scroll");
|
||
scroll.scrollTo({ top: scroll.scrollHeight, behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
|
||
});
|
||
|
||
function updateComposer() {
|
||
const text = $("message-input").value, count = Array.from(text).length;
|
||
$("message-count").textContent = `${count} / 4000`;
|
||
$("message-count").classList.toggle("over-limit", count > 4000);
|
||
$("pick-file").disabled = state.sending || uploadBusy;
|
||
$("send-message").disabled = state.sending || uploadBusy || (!text.trim() && !(attachedDrafts.get(state.current?.id)?.length)) || count > 4000;
|
||
$("message-input").style.height = "auto";
|
||
const height = $("message-input").scrollHeight + 2;
|
||
$("message-input").style.height = Math.min(140, height) + "px";
|
||
$("message-input").style.overflowY = height > 140 ? "auto" : "hidden";
|
||
if (state.current) state.drafts.set(state.current.id, text);
|
||
}
|
||
|
||
$("message-input").addEventListener("input", updateComposer);
|
||
$("message-input").addEventListener("keydown", event => {
|
||
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
||
event.preventDefault();
|
||
if (!$("send-message").disabled) $("message-form").requestSubmit();
|
||
}
|
||
});
|
||
$("message-form").addEventListener("submit", async event => {
|
||
event.preventDefault();
|
||
if (state.sending || !state.current || $("send-message").disabled) return;
|
||
const epoch = state.epoch, chatId = state.current.id, text = $("message-input").value;
|
||
const attachment_ids = (attachedDrafts.get(chatId) || []).map(file => file.id);
|
||
const previous = pendingMessages.get(chatId);
|
||
const attempt = previous?.text === text && JSON.stringify(previous.attachment_ids) === JSON.stringify(attachment_ids) ? previous : { text, attachment_ids, key: crypto.randomUUID() };
|
||
pendingMessages.set(chatId, attempt);
|
||
state.sending = true; updateComposer(); renderAttachedDrafts();
|
||
try {
|
||
const message = await request(`/api/v1/chats/${chatId}/messages`, {
|
||
method: "POST", body: { text, attachment_ids }, headers: { "Idempotency-Key": attempt.key }
|
||
});
|
||
pendingMessages.delete(chatId);
|
||
clearAttachedDrafts(chatId);
|
||
renderAttachedDrafts();
|
||
if (state.drafts.get(chatId) === text) state.drafts.set(chatId, "");
|
||
if (epoch !== state.epoch) return;
|
||
state.messages.set(message.id, message);
|
||
updateChatPreview(chatId, [message]);
|
||
if ($("message-input").value === text) $("message-input").value = "";
|
||
renderMessages("bottom");
|
||
await syncRecent(false, true);
|
||
} catch (error) { toast(error.status === 0 ? "Ответ не получен. Повторите отправку: сообщение не продублируется." : error.message, true); }
|
||
finally { state.sending = false; updateComposer(); renderAttachedDrafts(); }
|
||
});
|
||
|
||
function openNewChat() {
|
||
$("new-chat-form").reset(); notice("chat-dialog-notice", "");
|
||
$("new-chat-dialog").showModal(); $("new-chat-title").focus();
|
||
}
|
||
$("new-chat").addEventListener("click", openNewChat);
|
||
$("welcome-new-chat").addEventListener("click", openNewChat);
|
||
document.querySelectorAll("[data-close-dialog]").forEach(button => button.addEventListener("click", () => button.closest("dialog").close()));
|
||
$("new-chat-form").addEventListener("submit", async event => {
|
||
event.preventDefault();
|
||
const form = event.currentTarget, token = state.session?.token;
|
||
const title = $("new-chat-title").value.trim();
|
||
if (!title || Array.from(title).length > 100) return notice("chat-dialog-notice", "Название должно содержать от 1 до 100 символов.");
|
||
const ids = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean);
|
||
if (ids.some(id => !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id)))
|
||
return notice("chat-dialog-notice", "Проверьте ID участников: нужен полный ID из профиля.");
|
||
const members = [...new Set([state.session.user.id, ...ids.map(id => id.toLowerCase())])];
|
||
if (members.length > 100) return notice("chat-dialog-notice", "В чате может быть не более 100 участников.");
|
||
setFormBusy(form, true); notice("chat-dialog-notice", "");
|
||
try {
|
||
const chat = await request("/api/v1/chats", { method: "POST", body: { title, member_ids: members } });
|
||
if (token !== state.session?.token) return;
|
||
$("new-chat-dialog").close(); state.chats.push(chat); renderChats();
|
||
await selectChat(chat); toast("Чат создан.");
|
||
} catch (error) { notice("chat-dialog-notice", error.message); }
|
||
finally { setFormBusy(form, false); }
|
||
});
|
||
|
||
$("open-profile").addEventListener("click", () => {
|
||
$("profile-details").textContent = state.session.user.display_name + " · @" + state.session.user.username;
|
||
$("my-id").value = state.session.user.id; $("profile-dialog").showModal();
|
||
});
|
||
$("copy-id").addEventListener("click", async () => {
|
||
try { await navigator.clipboard.writeText(state.session.user.id); toast("ID скопирован."); }
|
||
catch { $("my-id").select(); toast("Выделили ID. Скопируйте его сочетанием ⌘C или Ctrl+C."); }
|
||
});
|
||
$("show-members").addEventListener("click", () => {
|
||
$("members-list").replaceChildren(...state.current.member_ids.map(id => {
|
||
const item = document.createElement("div"); item.className = "member-item";
|
||
const label = document.createElement("strong"); label.textContent = (state.members.get(id)?.display_name || "Участник") + (id === state.session.user.id ? " (вы)" : "");
|
||
const avatar = document.createElement("span"); avatar.className = "avatar";
|
||
paintAvatar(avatar, id, state.members.get(id)?.display_name || "Участник");
|
||
const details = document.createElement("span"); details.className = "member-details";
|
||
const code = document.createElement("code"); code.textContent = id; details.append(label, code); item.append(avatar, details); return item;
|
||
}));
|
||
$("members-dialog").showModal();
|
||
});
|
||
$("logout").addEventListener("click", async () => {
|
||
$("logout").disabled = true;
|
||
try { await request("/api/v1/auth/sessions/current", { method: "DELETE" }); endSession(); }
|
||
catch (error) { if (error.status !== 401) toast(error.message, true); }
|
||
finally { $("logout").disabled = false; }
|
||
});
|
||
$("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open"));
|
||
$("refresh-messages").addEventListener("click", async () => {
|
||
try { await syncRecent(); } catch (error) { toast(error.message, true); }
|
||
});
|
||
|
||
setInterval(async () => {
|
||
if (!state.session || document.hidden) return;
|
||
if (new Date(state.session.expires_at).getTime() <= Date.now()) return endSession("Сессия закончилась. Войдите снова.");
|
||
if (state.current) { try { await syncRecent(false, true); } catch { /* manual actions still show errors */ } }
|
||
if (!state.chatsCursor && state.chats.length <= 100 && Date.now() - lastChatRefresh > 12000) {
|
||
try { await loadChats(false, true); } catch { /* manual refresh shows errors */ }
|
||
}
|
||
}, 4000);
|
||
|
||
async function resume() {
|
||
try {
|
||
const stored = sessionStorage.getItem(storageKey);
|
||
if (!stored) return;
|
||
const session = JSON.parse(stored);
|
||
if (!session?.token || !session.user || !(new Date(session.expires_at).getTime() > Date.now())) return endSession();
|
||
state.session = session;
|
||
attachmentSession(session.token);
|
||
const user = await request("/api/v1/users/me");
|
||
await enterSession({ ...session, user });
|
||
} catch (error) {
|
||
state.session = null;
|
||
attachmentSession(null);
|
||
clearAttachedDrafts();
|
||
if (error instanceof ApiError) notice("auth-notice", error.message);
|
||
else { try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } }
|
||
}
|
||
}
|
||
|
||
void resume();
|
||
startClusterView(() => request('/api/ui/cluster', {background:true}), () => state.session?.token);
|
||
|
||
function clearAttachedDrafts(chatId) {
|
||
for (const [id, files] of attachedDrafts) {
|
||
if (chatId && id !== chatId) continue;
|
||
for (const file of files) {
|
||
file.removed = true;
|
||
if (file.previewUrl) URL.revokeObjectURL(file.previewUrl);
|
||
}
|
||
attachedDrafts.delete(id);
|
||
}
|
||
}
|
||
function renderAttachedDrafts() {
|
||
const root = $("attached-files"); root.replaceChildren();
|
||
for (const file of attachedDrafts.get(state.current?.id) || []) {
|
||
const item = document.createElement("div"); item.className = "draft-image";
|
||
const image = document.createElement("img"); image.src = file.previewUrl; image.alt = file.filename;
|
||
const label = document.createElement("span"); label.className="draft-image-name"; label.textContent=file.filename;label.title=file.filename;
|
||
const remove = document.createElement("button"); remove.type="button";remove.className="draft-image-remove";remove.textContent="×";
|
||
remove.setAttribute("aria-label","Убрать " + file.filename);remove.title="Убрать изображение";remove.disabled=state.sending;
|
||
remove.addEventListener("click",()=>{
|
||
const chat = state.current.id;
|
||
file.removed=true;URL.revokeObjectURL(file.previewUrl);
|
||
attachedDrafts.set(chat,(attachedDrafts.get(chat)||[]).filter(item=>item!==file));
|
||
renderAttachedDrafts();updateComposer();
|
||
});
|
||
item.append(image,label,remove);
|
||
if(!file.id) {
|
||
const status=document.createElement("span");status.className="draft-image-loading";status.textContent="Загрузка…";status.setAttribute("role","status");item.append(status);
|
||
}
|
||
root.append(item);
|
||
}
|
||
}
|
||
$("pick-file").addEventListener("click",()=>$("image-file").click());
|
||
$("image-file").addEventListener("change",async()=>{
|
||
const file=$("image-file").files[0];$("image-file").value="";
|
||
if(!file || !state.current || uploadBusy || state.sending) return;
|
||
if(file.size>10485760) {toast("Максимум 10 MiB",true);return;}
|
||
if(!["image/png","image/jpeg"].includes(file.type)) {toast("Выберите PNG или JPEG",true);return;}
|
||
if((attachedDrafts.get(state.current.id)||[]).length>=10) {toast("Максимум 10 вложений",true);return;}
|
||
const chat=state.current.id, session=state.session.token;
|
||
const draft={filename:file.name,previewUrl:URL.createObjectURL(file),id:null,removed:false};
|
||
attachedDrafts.set(chat,[...(attachedDrafts.get(chat)||[]),draft]);renderAttachedDrafts();
|
||
uploadBusy=true;$("pick-file").disabled=true;updateComposer();
|
||
try {
|
||
const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(file.name)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}});
|
||
if(state.session?.token!==session || draft.removed) return;
|
||
Object.assign(draft,attachment);renderAttachedDrafts();
|
||
}catch(error){
|
||
if(!draft.removed) {
|
||
draft.removed=true;URL.revokeObjectURL(draft.previewUrl);
|
||
attachedDrafts.set(chat,(attachedDrafts.get(chat)||[]).filter(item=>item!==draft));renderAttachedDrafts();
|
||
}
|
||
if(state.session?.token===session) toast(error.message,true);
|
||
}
|
||
finally {uploadBusy=false;$("pick-file").disabled=state.sending;updateComposer();}
|
||
});
|