260 lines
8.9 KiB
JavaScript
260 lines
8.9 KiB
JavaScript
// Channel, server and private text chat. Message text is rendered as plain text only.
|
|
import { $, h, icon, reconcile, setText, formatTime } from './dom.js';
|
|
import { S, isConnected, ownChannel, clientById } from './state.js';
|
|
import { call } from './core.js';
|
|
import { errorText, stripBBCode } from './text.js';
|
|
import { toast } from './toast.js';
|
|
|
|
const MAX_MESSAGES = 500;
|
|
const chats = new Map();
|
|
let active = 'channel';
|
|
|
|
function ensureChat(key, init) {
|
|
let chat = chats.get(key);
|
|
if (!chat) {
|
|
chat = { key, messages: [], unread: 0, ...init };
|
|
chats.set(key, chat);
|
|
}
|
|
return chat;
|
|
}
|
|
|
|
ensureChat('channel', { kind: 'channel' });
|
|
ensureChat('server', { kind: 'server' });
|
|
|
|
export function initChat() {
|
|
const form = $('#chat-form');
|
|
const input = $('#chat-input');
|
|
form.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
send();
|
|
});
|
|
input.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
|
|
e.preventDefault();
|
|
send();
|
|
}
|
|
});
|
|
input.addEventListener('input', autosize);
|
|
$('#chat-tabs').addEventListener('keydown', onTabKey);
|
|
}
|
|
|
|
function autosize() {
|
|
const input = $('#chat-input');
|
|
input.style.height = 'auto';
|
|
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
|
|
}
|
|
|
|
function tabTitle(chat) {
|
|
if (chat.kind === 'channel') return ownChannel()?.name ?? 'Канал';
|
|
if (chat.kind === 'server') return 'Сервер';
|
|
const cl = clientById(chat.clientId);
|
|
return cl ? cl.nickname : `${chat.nickname} (вышел)`;
|
|
}
|
|
|
|
function targetOf(chat) {
|
|
if (chat.kind === 'client') return { target: 'client', client_id: chat.clientId };
|
|
return { target: chat.kind };
|
|
}
|
|
|
|
async function send() {
|
|
const input = $('#chat-input');
|
|
const text = input.value.replace(/\s+$/u, '');
|
|
if (!text.trim() || !isConnected()) return;
|
|
const chat = chats.get(active);
|
|
if (!chat) return;
|
|
if (chat.kind === 'client' && !clientById(chat.clientId)) {
|
|
toast('Собеседник покинул сервер', 'error');
|
|
return;
|
|
}
|
|
if (new TextEncoder().encode(text).length > 8192) {
|
|
toast('Сообщение длиннее 8 КиБ', 'error');
|
|
return;
|
|
}
|
|
input.disabled = true;
|
|
try {
|
|
await call('send_text', { ...targetOf(chat), message: text });
|
|
input.value = '';
|
|
autosize();
|
|
} catch (err) {
|
|
toast(`Сообщение не отправлено: ${errorText(err)}`, 'error');
|
|
} finally {
|
|
input.disabled = false;
|
|
input.focus();
|
|
}
|
|
}
|
|
|
|
/** Incoming `text` event (bridge §5). Our own messages arrive here too, exactly once. */
|
|
export function onText(evt) {
|
|
const own = S.snap?.own_client_id;
|
|
let key;
|
|
if (evt.target === 'channel') key = 'channel';
|
|
else if (evt.target === 'server') key = 'server';
|
|
else {
|
|
const other = evt.from_client_id === own ? evt.to_client_id : evt.from_client_id;
|
|
if (!Number.isInteger(other)) return;
|
|
key = openPrivate(other, { focus: false, nickname: evt.from_client_id === own ? undefined : evt.from_nickname });
|
|
}
|
|
addMessage(key, {
|
|
author: evt.from_nickname ?? '?',
|
|
own: evt.from_client_id === own,
|
|
authorId: evt.from_client_id,
|
|
text: stripBBCode(evt.message),
|
|
});
|
|
}
|
|
|
|
export function addSystem(key, text) {
|
|
addMessage(key, { system: true, text });
|
|
}
|
|
|
|
function addMessage(key, msg) {
|
|
const chat = chats.get(key);
|
|
if (!chat) return;
|
|
msg.time = new Date();
|
|
msg.id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
chat.messages.push(msg);
|
|
if (chat.messages.length > MAX_MESSAGES) chat.messages.splice(0, chat.messages.length - MAX_MESSAGES);
|
|
if (key === active && S.view === 'main') {
|
|
appendRow(chat, msg);
|
|
} else if (!msg.system && !msg.own) {
|
|
chat.unread += 1;
|
|
}
|
|
renderTabs();
|
|
}
|
|
|
|
/** Opens (or creates) a private conversation; returns its key. */
|
|
export function openPrivate(clientId, { focus = true, nickname } = {}) {
|
|
const key = `client:${clientId}`;
|
|
const cl = clientById(clientId);
|
|
const chat = ensureChat(key, { kind: 'client', clientId, nickname: nickname ?? cl?.nickname ?? '?' });
|
|
if (cl) chat.nickname = cl.nickname;
|
|
if (focus) {
|
|
select(key);
|
|
$('#chat-input').focus();
|
|
} else {
|
|
renderTabs();
|
|
}
|
|
return key;
|
|
}
|
|
|
|
function select(key) {
|
|
if (!chats.has(key)) return;
|
|
active = key;
|
|
chats.get(key).unread = 0;
|
|
renderTabs();
|
|
renderLog();
|
|
}
|
|
|
|
function closePrivate(key) {
|
|
chats.delete(key);
|
|
if (active === key) active = 'channel';
|
|
renderTabs();
|
|
renderLog();
|
|
}
|
|
|
|
export function renderTabs() {
|
|
const host = $('#chat-tabs');
|
|
const list = Array.from(chats.values());
|
|
reconcile(host, list, (c) => c.key, createTab, updateTab);
|
|
updateComposer();
|
|
}
|
|
|
|
function createTab(chat) {
|
|
const tab = h('button', { class: 'chat-tab', type: 'button', role: 'tab' }, h('span', { class: 'tab-label' }), h('span', { class: 'unread', hidden: true }));
|
|
tab.addEventListener('click', () => select(chat.key));
|
|
const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab);
|
|
if (chat.kind === 'client') {
|
|
const close = h('button', { class: 'tab-close icon-btn', type: 'button', 'aria-label': 'Закрыть личный чат' }, icon('x'));
|
|
close.addEventListener('click', () => closePrivate(chat.key));
|
|
wrap.appendChild(close);
|
|
}
|
|
return wrap;
|
|
}
|
|
|
|
function updateTab(wrap, chat) {
|
|
const tab = wrap.firstElementChild;
|
|
const [label, unread] = tab.children;
|
|
const title = tabTitle(chat);
|
|
setText(label, chat.kind === 'client' ? `@ ${title}` : title);
|
|
const selected = chat.key === active;
|
|
tab.setAttribute('aria-selected', String(selected));
|
|
tab.tabIndex = selected ? 0 : -1;
|
|
tab.title = chat.kind === 'channel' ? 'Чат текущего канала' : chat.kind === 'server' ? 'Чат всего сервера' : `Личные сообщения: ${title}`;
|
|
unread.hidden = chat.unread === 0;
|
|
setText(unread, chat.unread > 99 ? '99+' : String(chat.unread));
|
|
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? `, непрочитанных: ${chat.unread}` : ''}`);
|
|
}
|
|
|
|
function onTabKey(e) {
|
|
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
|
|
const tabs = Array.from(document.querySelectorAll('#chat-tabs [role="tab"]'));
|
|
const idx = tabs.indexOf(document.activeElement);
|
|
if (idx < 0) return;
|
|
const next = tabs[(idx + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
|
|
next.focus();
|
|
next.click();
|
|
e.preventDefault();
|
|
}
|
|
|
|
export function renderLog() {
|
|
const log = $('#chat-log');
|
|
const chat = chats.get(active);
|
|
log.replaceChildren();
|
|
if (!chat || chat.messages.length === 0) {
|
|
log.appendChild(h('li', { class: 'chat-empty', text: emptyText(chat) }));
|
|
updateComposer();
|
|
return;
|
|
}
|
|
let prev = null;
|
|
for (const msg of chat.messages) {
|
|
log.appendChild(rowFor(msg, prev));
|
|
prev = msg;
|
|
}
|
|
log.scrollTop = log.scrollHeight;
|
|
updateComposer();
|
|
}
|
|
|
|
function emptyText(chat) {
|
|
if (!chat) return '';
|
|
if (chat.kind === 'channel') return 'Сообщения в этом канале видят все, кто в нём находится.';
|
|
if (chat.kind === 'server') return 'Сообщения сервера видят все подключённые.';
|
|
return 'Личная переписка. Сообщения видит только собеседник.';
|
|
}
|
|
|
|
function rowFor(msg, prev) {
|
|
if (msg.system) return h('li', { class: 'msg-system', text: msg.text });
|
|
const head = !prev || prev.system || prev.authorId !== msg.authorId || msg.time - prev.time > 5 * 60 * 1000;
|
|
const li = h('li', { class: 'msg', dataset: { head: String(head), own: String(Boolean(msg.own)) } });
|
|
if (head) {
|
|
li.appendChild(h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: msg.author }), h('time', { class: 'msg-time', datetime: msg.time.toISOString(), text: formatTime(msg.time) })));
|
|
}
|
|
li.appendChild(h('div', { class: 'msg-body', text: msg.text }));
|
|
return li;
|
|
}
|
|
|
|
function appendRow(chat, msg) {
|
|
const log = $('#chat-log');
|
|
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
|
const empty = log.querySelector('.chat-empty');
|
|
if (empty) empty.remove();
|
|
const prev = chat.messages[chat.messages.length - 2] ?? null;
|
|
log.appendChild(rowFor(msg, prev));
|
|
if (nearBottom || msg.own) log.scrollTop = log.scrollHeight;
|
|
}
|
|
|
|
export function updateComposer() {
|
|
const input = $('#chat-input');
|
|
const sendBtn = $('#chat-send');
|
|
const chat = chats.get(active);
|
|
const partnerGone = chat && chat.kind === 'client' && !clientById(chat.clientId);
|
|
const enabled = isConnected() && !partnerGone;
|
|
input.disabled = !enabled;
|
|
sendBtn.disabled = !enabled;
|
|
const title = chat ? tabTitle(chat) : '';
|
|
input.placeholder = !isConnected() ? 'Нет подключения' : partnerGone ? 'Собеседник покинул сервер' : chat?.kind === 'client' ? `Сообщение для ${title}` : chat?.kind === 'server' ? 'Сообщение всему серверу' : `Сообщение в «${title}»`;
|
|
}
|
|
|
|
/** Called when the connection ends: private chats keep their history but cannot be answered. */
|
|
export function onConnectionChanged() {
|
|
renderTabs();
|
|
}
|