604 lines
31 KiB
JavaScript
604 lines
31 KiB
JavaScript
import { t, getLanguage, onLanguageChange } from './i18n.js';
|
|
import { $, h, icon, reconcile, setText } from './dom.js';
|
|
import { S, viewedConnection, ownClient, ownChannel, clientById, isConnected, isAlive, on, emit } from './state.js';
|
|
import { callOn, tp } from './core.js';
|
|
import { errorText } from './text.js';
|
|
import { toast } from './toast.js';
|
|
import { renderMarkdownInto, findTs3Files, applyImageSize } from './markdown/render.js';
|
|
import { setMermaidAutoload } from './markdown/mermaid.js';
|
|
import { handleMarkdownClick, handleMarkdownKey } from './chat-markdown-help.js';
|
|
import { requestServerFileDownload, fetchServerImage, chooseAndUploadChatAttachments, canAttachFiles } from './files.js';
|
|
import { initChatComposer } from './chat-composer.js';
|
|
import { createChatEditor } from './chat-editor.js';
|
|
import { notify } from './notifications.js';
|
|
import { initChatSettings, setIgnoredUser } from './chat-settings.js';
|
|
import { formatClock, showsMessage, opensIncoming, isIgnoredText, isIgnoredUid } from './chat-options.js';
|
|
import { openAdminAction } from './admin.js';
|
|
import { avatarUrl } from './media.js';
|
|
import { senderColor } from './chat-colors.js';
|
|
|
|
const MAX_MESSAGES = 500;
|
|
const PAGE = 100;
|
|
const states = new Map();
|
|
let displayed = null;
|
|
let controls;
|
|
let privateInfo;
|
|
let lastBadge = -1;
|
|
let closeComposer = () => {};
|
|
// The single composer editor (chat-editor.js adapter); its contentDOM is #chat-input.
|
|
let editor = null;
|
|
const imageUrls = new Set();
|
|
|
|
function stateFor(conn) {
|
|
if (!conn) return null;
|
|
const identity = ownClient(conn)?.uid;
|
|
const server = conn.snap?.server?.uid;
|
|
let state = states.get(conn);
|
|
if (!state || (identity && server && (state.base?.identity !== identity || state.base?.server !== server))) {
|
|
state = { conn, base: identity && server ? { identity, server } : null, chats: new Map(), active: 'channel', restored: false };
|
|
states.set(conn, state);
|
|
}
|
|
const cid = conn.snap?.own_channel_id;
|
|
if (cid) {
|
|
const key = `channel:${cid}`;
|
|
ensureChat(state, key, 'channel', String(cid), ownChannel(conn)?.name ?? '');
|
|
if (state.active === 'channel' || state.lastChannel !== cid && state.active === `channel:${state.lastChannel}`) state.active = key;
|
|
state.lastChannel = cid;
|
|
}
|
|
ensureChat(state, 'server', 'server', 'server', '');
|
|
return state;
|
|
}
|
|
|
|
function ensureChat(state, key, kind, scopeKey, nickname) {
|
|
let chat = state.chats.get(key);
|
|
if (!chat) {
|
|
chat = { state, key, kind, nickname, scope: state.base ? { ...state.base, kind, key: scopeKey } : null,
|
|
messages: [], unread: 0, draft: '', loaded: false, loading: false, older: false, before: 0, total: 0, queue: Promise.resolve(), sending: false };
|
|
state.chats.set(key, chat);
|
|
}
|
|
if (nickname) chat.nickname = nickname;
|
|
return chat;
|
|
}
|
|
|
|
function current() { const state = stateFor(viewedConnection()); return state?.chats.get(state.active) ?? null; }
|
|
function visible(chat) { return current() === chat && S.view === 'main'; }
|
|
function report(err) { toast(() => t('chat.operation_failed', { error: errorText(err) }), 'error'); }
|
|
function checked(result) { if (!result?.ok) throw new Error(result?.error?.message ?? 'Chat history unavailable'); return result; }
|
|
function persistOpen(chat, open) {
|
|
if (chat.scope) tp.chatHistorySetOpen(chat.scope, open, chat.nickname).then(checked).catch(report);
|
|
}
|
|
|
|
// A global message budget, not 500 messages for every private tab/server ever visited.
|
|
function trimMemory(protectedChat) {
|
|
let count = 0;
|
|
for (const state of states.values()) for (const chat of state.chats.values()) count += chat.messages.length;
|
|
for (const state of states.values()) for (const chat of state.chats.values()) {
|
|
if (count <= MAX_MESSAGES) return;
|
|
if (chat === protectedChat || chat === current()) continue;
|
|
count -= chat.messages.length;
|
|
chat.messages = [];
|
|
chat.loaded = false;
|
|
}
|
|
if (count > MAX_MESSAGES && protectedChat) protectedChat.messages.splice(0, count - MAX_MESSAGES);
|
|
}
|
|
|
|
async function loadPage(chat, before = -1) {
|
|
if (!chat?.scope || chat.loading) return;
|
|
chat.loading = true;
|
|
if (visible(chat)) renderHistoryControls(chat);
|
|
try {
|
|
await chat.queue;
|
|
const result = checked(await tp.chatHistoryPage(chat.scope, before, PAGE));
|
|
if (states.get(chat.state.conn) !== chat.state) return;
|
|
const pending = before === -1 ? chat.messages.filter((m) => m.index == null || m.index >= result.total) : [];
|
|
const records = result.messages.map((m) => ({ ...m, author: m.from_name, authorUid: m.from_uid, time: new Date(m.time) }));
|
|
chat.messages = [...records, ...pending].slice(-MAX_MESSAGES);
|
|
chat.before = result.start ?? 0;
|
|
chat.total = result.total;
|
|
chat.older = before !== -1;
|
|
chat.loaded = true;
|
|
trimMemory(chat);
|
|
if (visible(chat)) renderLog();
|
|
} catch (err) { report(err); }
|
|
finally { chat.loading = false; if (visible(chat)) renderHistoryControls(chat); }
|
|
}
|
|
|
|
async function restore(state) {
|
|
if (!state.base || state.restored) return;
|
|
state.restored = true;
|
|
try {
|
|
const result = checked(await tp.chatHistoryList(state.base));
|
|
if (states.get(state.conn) !== state) return;
|
|
for (const item of result.conversations) {
|
|
if (item.kind === 'client' && item.open) ensureChat(state, `client:${item.key}`, 'client', item.key, item.label);
|
|
}
|
|
if (viewedConnection() === state.conn) renderTabs();
|
|
} catch (err) { state.restored = false; report(err); }
|
|
}
|
|
|
|
export function initChat() {
|
|
$('#chat-form').addEventListener('submit', (e) => { e.preventDefault(); void send(); });
|
|
editor = createChatEditor($('#chat-editor'));
|
|
editor.setPreview(richTextEditing());
|
|
editor.addEventListener('input', () => { if (displayed) displayed.draft = editor.value; updateComposer(); });
|
|
// Plain Enter is not in CodeMirror's keymap: this listener sends; Shift+Enter stays a newline.
|
|
editor.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.defaultPrevented) { e.preventDefault(); void send(); }
|
|
});
|
|
$('#chat-tabs')?.addEventListener('keydown', onTabKey);
|
|
privateInfo = h('button', { id: 'chat-client-info', type: 'button', class: 'icon-btn', hidden: true, 'aria-label': t('admin.info'), title: t('admin.info') }, icon('mode-info'));
|
|
privateInfo.addEventListener('click', () => {
|
|
const chat = current();
|
|
if (chat?.kind !== 'client' || !isConnected(chat.state.conn)) return;
|
|
const conn = chat.state.conn;
|
|
const client = partner(chat);
|
|
if (!client) return;
|
|
void openAdminAction('client.info', { connectionId: conn.id, clientId: client.id });
|
|
});
|
|
document.querySelector('.detail-modes').prepend(privateInfo);
|
|
controls = h('div', { class: 'chat-history-controls' });
|
|
$('#chat-log').before(controls);
|
|
$('#chat-log').addEventListener('click', handleMarkdownClick);
|
|
$('#chat-log').addEventListener('keydown', handleMarkdownKey);
|
|
closeComposer = initChatComposer({ editor, onChange: () => { if (displayed) displayed.draft = editor.value; updateComposer(); }, attach });
|
|
$('#chat-form').append(h('div', { id: 'chat-start-prompt', class: 'chat-start-prompt', hidden: true }, icon('mode-chat'), h('span')));
|
|
on('appearance-changed', renderLog);
|
|
on('server_event', onChannelEvent);
|
|
onLanguageChange(renderLog);
|
|
initChatSettings(() => { renderLog(); updateComposer(); });
|
|
editor.addEventListener('focus', updateComposer);
|
|
$('#chat-form').addEventListener('focusout', () => queueMicrotask(updateComposer));
|
|
const composer = $('#chat-form');
|
|
const log = $('#chat-log');
|
|
let bottomPinned = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
|
let measuredWidth = log.clientWidth, measuredHeight = log.clientHeight;
|
|
// Reflow can emit a scroll event before ResizeObserver. It is not a change in reading intent.
|
|
log.addEventListener('scroll', () => {
|
|
if (log.clientWidth === measuredWidth && log.clientHeight === measuredHeight)
|
|
bottomPinned = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
|
}, { passive: true });
|
|
const resize = new ResizeObserver((entries) => {
|
|
const measurement = entries.find(entry => entry.target === composer);
|
|
if (measurement) composer.closest('.chat').style.setProperty('--composer-height', `calc(${measurement.contentRect.height}px + 2 * var(--tsv-padding-h-small))`);
|
|
// The original virtual list overlays its scrollbar inside the 10px safe area; native lists reserve its width.
|
|
log.style.setProperty('--chat-scrollbar-width', `${log.offsetWidth - log.clientWidth}px`);
|
|
if (bottomPinned) log.scrollTop = log.scrollHeight;
|
|
measuredWidth = log.clientWidth; measuredHeight = log.clientHeight;
|
|
});
|
|
resize.observe(composer);
|
|
resize.observe(log);
|
|
on('show-server-chat', () => {
|
|
const state = stateFor(viewedConnection());
|
|
if (!state) return;
|
|
state.chats.get('server').opened = true;
|
|
select(state, 'server');
|
|
});
|
|
onViewChanged();
|
|
}
|
|
|
|
/** workflowSettings.useRichTextEditor (default true): hybrid Markdown preview, otherwise raw source. */
|
|
function richTextEditing() { return S.prefs?.chatRichTextEditor !== false; }
|
|
/** The composer adapter for callers that move focus into the chat (app.js) or inspect it. */
|
|
export function composerEditor() { return editor; }
|
|
function partner(chat) { return chat.state.conn.snap?.clients.find((c) => c.uid === chat.scope?.key) ?? null; }
|
|
function tabTitle(chat) {
|
|
if (chat.kind === 'channel') return chat.state.conn.snap?.channels.find((c) => String(c.id) === chat.scope?.key)?.name ?? chat.nickname ?? t('ui.channel');
|
|
if (chat.kind === 'server') return t('ui.server');
|
|
return partner(chat)?.nickname ?? chat.nickname;
|
|
}
|
|
function canSend(chat) {
|
|
return Boolean(chat && isAlive(chat.state.conn) && isConnected(chat.state.conn) && !chat.sending
|
|
&& (chat.kind !== 'client' || partner(chat))
|
|
&& (chat.kind !== 'channel' || String(chat.state.conn.snap.own_channel_id) === chat.scope?.key));
|
|
}
|
|
|
|
async function send() {
|
|
const chat = current();
|
|
const text = editor.value.replace(/\s+$/u, '');
|
|
if (!text.trim() || !canSend(chat)) return;
|
|
if (new TextEncoder().encode(text).length > 8192) { toast(() => t('ui.message.exceeds.8.kib'), 'error'); return; }
|
|
const conn = chat.state.conn;
|
|
const session = conn.session;
|
|
const target = chat.kind === 'client' ? { target: 'client', client_id: partner(chat).id, expected_client_uid: chat.scope.key } : { target: chat.kind };
|
|
chat.sending = true;
|
|
updateComposer();
|
|
try {
|
|
await callOn(conn.id, 'send_text', { ...target, message: text });
|
|
if (!isAlive(conn) || conn.session !== session) return;
|
|
notify('message_sent', conn);
|
|
chat.draft = '';
|
|
if (current() === chat && editor.value.replace(/\s+$/u, '') === text) editor.value = '';
|
|
} catch (err) { report(err); }
|
|
finally { chat.sending = false; if (current() === chat) updateComposer(); }
|
|
}
|
|
|
|
export function onText(evt, conn) {
|
|
const state = stateFor(conn);
|
|
if (!state) return;
|
|
// Ignored users (Settings > Chats): their messages and pokes are dropped before any chat state or history changes.
|
|
if (isIgnoredText(evt, conn, S.prefs)) return;
|
|
const own = conn.snap?.own_client_id;
|
|
let chat;
|
|
if (evt.target === 'channel') chat = state.chats.get(`channel:${conn.snap?.own_channel_id}`);
|
|
else if (evt.target === 'server') chat = state.chats.get('server');
|
|
else {
|
|
const outgoing = evt.from_client_id === own;
|
|
const other = outgoing ? evt.to_client_id : evt.from_client_id;
|
|
// Official openIncomingChats: incoming chats join the sidebar list without taking focus; when off they stay
|
|
// out of the list and are only counted as unread until opened.
|
|
const key = openPrivate(conn, other, { focus: false, reveal: outgoing || opensIncoming(S.prefs), nickname: outgoing ? undefined : evt.from_nickname });
|
|
chat = state.chats.get(key);
|
|
}
|
|
if (!chat) return;
|
|
const msg = { author: evt.from_nickname ?? '?', authorUid: evt.from_uid ?? clientById(evt.from_client_id, conn)?.uid ?? null,
|
|
own: evt.from_client_id === own, text: String(evt.message ?? '').slice(0, 32768), time: new Date() };
|
|
addMessage(chat, msg);
|
|
if (chat.scope) {
|
|
const record = { time: +msg.time, type: 'text', from_uid: msg.authorUid, from_name: msg.author.slice(0, 128), own: msg.own, text: msg.text };
|
|
chat.queue = chat.queue.then(async () => {
|
|
const result = checked(await tp.chatHistoryAppend(chat.scope, record, chat.nickname.slice(0, 128)));
|
|
msg.index = result.index;
|
|
chat.total = result.total;
|
|
if (!chat.older) chat.before = chat.messages.find((m) => m.index != null)?.index ?? 0;
|
|
if (visible(chat)) renderHistoryControls(chat);
|
|
}).catch(report);
|
|
}
|
|
}
|
|
|
|
export function addSystem(conn, key, text, { emphasis = [] } = {}) {
|
|
const state = stateFor(conn);
|
|
const chat = state?.chats.get(key === 'channel' ? `channel:${state.lastChannel}` : key);
|
|
if (chat) addMessage(chat, { system: true, text, emphasis: emphasis.filter((name) => typeof name === 'string' && name.length > 0), time: new Date() });
|
|
}
|
|
|
|
function onChannelEvent(event, conn) {
|
|
if (!conn || !['client_enter', 'client_leave', 'client_move'].includes(event.kind)) return;
|
|
const state = stateFor(conn);
|
|
if (!state || (event.kind === 'client_enter' && event.is_self)) return;
|
|
const victim = event.nickname ?? clientById(event.client_id, conn)?.nickname ?? '';
|
|
const invoker = event.invoker?.name ?? victim;
|
|
const byInvoker = Boolean(event.invoker?.name);
|
|
const reason = event.message ?? '';
|
|
for (const chat of state.chats.values()) {
|
|
if (chat.kind !== 'channel') continue;
|
|
const id = Number(chat.scope?.key);
|
|
const entering = event.to_channel_id === id;
|
|
const leaving = event.from_channel_id === id;
|
|
if (!entering && !leaving) continue;
|
|
const other = entering ? event.from_channel_id : event.to_channel_id;
|
|
const channel = conn.snap?.channels.find((entry) => entry.id === other)?.name ?? String(other ?? '');
|
|
let key;
|
|
if (event.kind === 'client_enter') key = 'channel.chat.events.client.joined';
|
|
else if (event.kind === 'client_leave') {
|
|
if (event.reason === 'ban') key = 'channel.chat.events.client.banned';
|
|
else if (event.reason === 'kick_server') key = 'channel.chat.events.client.kicked.from';
|
|
else key = event.reason === 'lost_connection' ? 'server.log.events.client.timeout' : 'server.log.events.client.disconnected';
|
|
if (['ban', 'kick_server'].includes(event.reason)) {
|
|
if (byInvoker) key += '.by_invoker';
|
|
if (reason) key += '.with_reason';
|
|
}
|
|
} else if (event.reason === 'kick_channel') {
|
|
key = entering ? 'channel.chat.events.client.kicked.into' : 'channel.chat.events.client.kicked.from_to';
|
|
if (leaving && byInvoker) key += '.by_invoker';
|
|
if (reason) key += '.with_reason';
|
|
} else if (event.reason === 'moved') {
|
|
key = entering ? 'channel.chat.events.client.moved.into' : 'channel.chat.events.client.moved.from';
|
|
if (byInvoker) key += '.by_invoker';
|
|
} else key = entering ? 'channel.chat.events.client.joined.from_channel' : 'channel.chat.events.client.left';
|
|
const params = { victim, invoker, channel, reason };
|
|
addMessage(chat, { system: true, moderation: true, text: () => t(key, params), emphasis: [victim, invoker, channel].filter(Boolean), time: new Date() });
|
|
}
|
|
}
|
|
function addMessage(chat, msg) {
|
|
chat.messages.push(msg);
|
|
if (chat.messages.length > MAX_MESSAGES) chat.messages.shift();
|
|
trimMemory(chat);
|
|
if (!visible(chat) || chat.older) { if (!msg.system && !msg.own) chat.unread += 1; }
|
|
if (visible(chat) && !chat.older) appendRow(chat, msg);
|
|
renderTabs();
|
|
badge();
|
|
}
|
|
|
|
/** `reveal: false` keeps a newly created chat out of the sidebar list (openIncomingChats off); focus always reveals. */
|
|
export function openPrivate(conn, clientId, { focus = true, reveal = true, nickname } = {}) {
|
|
const state = stateFor(conn);
|
|
const client = clientById(clientId, conn);
|
|
// Ephemeral numeric client IDs are never durable identity keys.
|
|
if (!state || !client?.uid) return null;
|
|
const key = `client:${client.uid}`;
|
|
const existing = state.chats.has(key);
|
|
const chat = ensureChat(state, key, 'client', client.uid, nickname ?? client.nickname);
|
|
if (focus || reveal) revealChat(chat);
|
|
else if (!existing) chat.hidden = true;
|
|
if (focus) select(state, key);
|
|
else renderTabs();
|
|
return key;
|
|
}
|
|
function revealChat(chat) {
|
|
chat.hidden = false;
|
|
persistOpen(chat, true);
|
|
}
|
|
function select(state, key) {
|
|
if (!state.chats.has(key)) return;
|
|
if (displayed) displayed.draft = editor.value;
|
|
state.active = key;
|
|
emit('set-view', 'main');
|
|
onViewChanged();
|
|
}
|
|
function closePrivate(chat) {
|
|
persistOpen(chat, false);
|
|
chat.state.chats.delete(chat.key);
|
|
if (chat.state.active === chat.key) chat.state.active = `channel:${chat.state.lastChannel}`;
|
|
onViewChanged();
|
|
}
|
|
|
|
export function selectedConversation() {
|
|
const chat = current();
|
|
return chat ? { kind: chat.kind, title: tabTitle(chat), client: chat.kind === 'client' ? partner(chat) : null } : null;
|
|
}
|
|
|
|
export function showOwnChannel() {
|
|
const state = stateFor(viewedConnection());
|
|
if (state) select(state, `channel:${state.lastChannel}`);
|
|
}
|
|
export function renderTabs() {
|
|
const state = stateFor(viewedConnection());
|
|
const host = $('#chat-tabs');
|
|
const conversations = [...(state?.chats.values() ?? [])].filter((chat) => chat.kind !== 'channel' && (chat.kind === 'client' ? !chat.hidden : chat.opened || chat.messages.some((message) => !message.system)));
|
|
if (host) reconcile(host, conversations, (c) => `${c.state.conn.id}:${c.scope?.identity}:${c.scope?.server}:${c.key}`, createTab, updateTab);
|
|
$('#conversations-panel').hidden = conversations.length === 0;
|
|
if (privateInfo) {
|
|
const chat = state?.chats.get(state.active);
|
|
privateInfo.hidden = chat?.kind !== 'client';
|
|
privateInfo.disabled = !chat || !isConnected(state.conn) || !partner(chat);
|
|
}
|
|
updateComposer();
|
|
emit('chat-selection');
|
|
}
|
|
function createTab(chat) {
|
|
const tab = h('button', { class: 'chat-tab', type: 'button', role: 'tab' }, icon(chat.kind === 'client' ? 'self-avatar' : 'server'), h('span', { class: 'tab-label' }), h('span', { class: 'unread', hidden: true }));
|
|
tab.addEventListener('click', () => select(chat.state, 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': t('ui.close.private.chat') }, icon('x'));
|
|
close.addEventListener('click', () => closePrivate(chat)); wrap.append(close);
|
|
}
|
|
return wrap;
|
|
}
|
|
function updateTab(wrap, chat) {
|
|
const tab = wrap.firstElementChild;
|
|
const [, label, unread] = tab.children;
|
|
const selected = chat.state.active === chat.key;
|
|
setText(label, () => tabTitle(chat));
|
|
tab.setAttribute('aria-selected', String(selected)); tab.tabIndex = selected ? 0 : -1;
|
|
unread.hidden = !chat.unread; unread.textContent = chat.unread > 99 ? '99+' : String(chat.unread);
|
|
tab.title = tabTitle(chat); tab.setAttribute('aria-label', `${tabTitle(chat)}${chat.unread ? t('message.unread.p0', { p0: chat.unread }) : ''}`);
|
|
}
|
|
function onTabKey(e) {
|
|
if (!['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(e.key)) return;
|
|
const tabs = [...document.querySelectorAll('#chat-tabs [role="tab"]')];
|
|
const idx = tabs.indexOf(document.activeElement); if (idx < 0) return;
|
|
const next = tabs[(idx + (e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : tabs.length - 1)) % tabs.length];
|
|
next.focus(); next.click(); e.preventDefault();
|
|
}
|
|
function renderHistoryControls(chat) {
|
|
if (!controls) return;
|
|
controls.replaceChildren();
|
|
if (!chat?.scope || (!chat.loading && chat.before === 0 && !chat.older)) return;
|
|
if (chat.before > 0 || chat.loading) {
|
|
const older = h('button', { type: 'button', class: 'btn', text: t('chat.history.older'), disabled: chat.loading });
|
|
older.addEventListener('click', () => loadPage(chat, chat.before));
|
|
controls.append(older);
|
|
}
|
|
if (chat.older) {
|
|
const latest = h('button', { type: 'button', class: 'btn', text: t('chat.history.latest'), disabled: chat.loading });
|
|
latest.addEventListener('click', () => { chat.unread = 0; void loadPage(chat); badge(); });
|
|
controls.append(latest);
|
|
}
|
|
}
|
|
export function renderLog() {
|
|
const log = $('#chat-log'); if (!log) return;
|
|
const chat = current();
|
|
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
|
const scrollTop = log.scrollTop;
|
|
for (const url of imageUrls) URL.revokeObjectURL(url); imageUrls.clear();
|
|
log.replaceChildren();
|
|
setMermaidAutoload(S.prefs?.chatMermaidAutoload);
|
|
// Hidden moderation events stay in memory, so turning the option back on shows them again.
|
|
const shown = chat?.messages.filter((msg) => showsMessage(msg, S.prefs)) ?? [];
|
|
if (!shown.length) log.append(h('li', { class: 'chat-empty', text: t('chat.history.empty') }));
|
|
else {
|
|
let prev = null;
|
|
for (const msg of shown) { log.append(rowFor(chat, msg, prev)); prev = msg; }
|
|
}
|
|
log.scrollTop = chat?.older ? 0 : nearBottom ? log.scrollHeight : scrollTop;
|
|
renderHistoryControls(chat); updateComposer();
|
|
}
|
|
function appendRow(chat, msg) {
|
|
const log = $('#chat-log');
|
|
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
|
|
const shown = chat.messages.filter((entry) => showsMessage(entry, S.prefs));
|
|
if (showsMessage(msg, S.prefs)) {
|
|
log.querySelector('.chat-empty')?.remove();
|
|
log.append(rowFor(chat, msg, shown.at(-2) ?? null));
|
|
}
|
|
// Rows mirror the shown messages; drop the rows of messages that left the front of the buffer.
|
|
const rows = () => log.querySelectorAll(':scope > .msg, :scope > .msg-system');
|
|
for (let extra = rows().length - shown.length; extra > 0; extra -= 1) {
|
|
const first = rows()[0];
|
|
for (const img of first.querySelectorAll('img')) {
|
|
if (imageUrls.delete(img.src)) URL.revokeObjectURL(img.src);
|
|
}
|
|
first.remove();
|
|
}
|
|
if (log.firstElementChild?.classList.contains('msg')) log.firstElementChild.dataset.head = 'true';
|
|
if (nearBottom || msg.own) log.scrollTop = log.scrollHeight;
|
|
renderHistoryControls(chat);
|
|
}
|
|
function messageTime(date, withDay = false) {
|
|
const locale = getLanguage();
|
|
const clock = formatClock(date, locale, S.prefs);
|
|
if (!withDay) return clock;
|
|
const today = new Date();
|
|
const day = (value) => Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / 86400000;
|
|
const distance = day(date) - day(today);
|
|
if (distance >= 2 && distance < 7) return date.toLocaleDateString(locale, { weekday: 'long' });
|
|
const suffix = distance >= -6 && distance < 2
|
|
? date.toLocaleDateString(locale, { weekday: 'short' })
|
|
: date.toLocaleDateString(locale, { year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
return `${clock} - ${suffix}`;
|
|
}
|
|
|
|
function messageAvatar(chat, msg) {
|
|
const face = h('span', { class: 'msg-avatar', 'aria-hidden': 'true' }, icon('self-avatar'));
|
|
const client = chat.state.conn.snap?.clients.find((entry) => entry.uid === msg.authorUid);
|
|
if (client) {
|
|
void avatarUrl(client, chat.state.conn).then((url) => {
|
|
if (url && face.isConnected) face.replaceChildren(h('img', { src: url, alt: '', draggable: 'false' }));
|
|
});
|
|
}
|
|
return h('span', { class: 'msg-avatar-wrapper' }, face);
|
|
}
|
|
|
|
function rowFor(chat, msg, prev) {
|
|
if (msg.system) {
|
|
const text = String((typeof msg.text === 'function' ? msg.text() : msg.text) ?? '');
|
|
const contents = h('span', { class: 'msg-system-text' });
|
|
// Only explicit event metadata is emphasized; server text is never interpreted as HTML.
|
|
const names = [...new Set(msg.emphasis ?? [])].sort((a, b) => b.length - a.length);
|
|
let offset = 0;
|
|
while (offset < text.length) {
|
|
let next = -1;
|
|
let name = '';
|
|
for (const candidate of names) {
|
|
const index = text.indexOf(candidate, offset);
|
|
if (index >= 0 && (next < 0 || index < next)) { next = index; name = candidate; }
|
|
}
|
|
if (next < 0) { contents.append(document.createTextNode(text.slice(offset))); break; }
|
|
contents.append(document.createTextNode(text.slice(offset, next)), h('strong', { text: name }));
|
|
offset = next + name.length;
|
|
}
|
|
const stamp = h('time', { class: 'msg-system-time', datetime: msg.time.toISOString(), text: messageTime(msg.time, true) });
|
|
return h('li', { class: 'msg-system' }, contents, stamp);
|
|
}
|
|
const head = !prev || prev.system || prev.authorUid !== msg.authorUid || prev.author !== msg.author || msg.time - prev.time > 30 * 60 * 1000;
|
|
const li = h('li', { class: 'msg', dataset: { head: String(head), own: String(Boolean(msg.own)) } });
|
|
const time = (withDay = false) => h('time', { class: 'msg-time', datetime: msg.time.toISOString(), text: messageTime(msg.time, withDay) });
|
|
const author = h('span', { class: 'msg-author', text: `${msg.author} ` });
|
|
author.style.color = senderColor(msg.author, getComputedStyle(document.documentElement).getPropertyValue('--tsv-bg'));
|
|
li.append(h('div', { class: 'msg-head' }, messageAvatar(chat, msg), author, time(true)));
|
|
const inlineTime = time(); inlineTime.classList.add('msg-inline-time'); li.append(inlineTime);
|
|
const body = h('div', { class: 'msg-body ts-parsed-text-content' });
|
|
const files = findTs3Files(msg.text);
|
|
if (!files.hideText) {
|
|
const result = renderMarkdownInto(body, msg.text);
|
|
li.classList.toggle('apparently-people-like-huge-faces', result.onlyEmoji);
|
|
}
|
|
for (const ref of files.files) {
|
|
const button = h('button', { type: 'button', class: 'chat-attachment', text: ref.name, disabled: ref.isDir || !isConnected(chat.state.conn) || ref.serverUid !== chat.state.base?.server });
|
|
button.addEventListener('click', async () => {
|
|
try { checked(await requestServerFileDownload(chat.state.conn.id, ref)); } catch (err) { report(err); }
|
|
});
|
|
body.append(button);
|
|
}
|
|
for (const wrap of body.querySelectorAll('.md-ts3image')) {
|
|
const button = wrap.querySelector('button');
|
|
button.addEventListener('click', async () => {
|
|
const conn = chat.state.conn; const session = conn.session;
|
|
button.disabled = true;
|
|
try {
|
|
const blob = await fetchServerImage(conn.id, { channelId: Number(wrap.dataset.channelId), path: wrap.dataset.path, name: wrap.dataset.name });
|
|
if (!isAlive(conn) || conn.session !== session || !wrap.isConnected) return;
|
|
const url = URL.createObjectURL(blob); imageUrls.add(url);
|
|
const img = h('img', { alt: wrap.dataset.alt || wrap.dataset.name }); img.src = url; wrap.replaceChildren(img);
|
|
applyImageSize(img, wrap.dataset.width, wrap.dataset.height);
|
|
} catch (err) { button.disabled = false; report(err); }
|
|
});
|
|
if (S.prefs?.autoDownloadImages === true && isConnected(chat.state.conn)) queueMicrotask(() => { if (wrap.isConnected) button.click(); });
|
|
}
|
|
li.append(body); return li;
|
|
}
|
|
export function updateComposer() {
|
|
if (!editor) return;
|
|
const chat = current(); const enabled = canSend(chat);
|
|
editor.setPreview(richTextEditing());
|
|
editor.disabled = !enabled; $('#chat-send').disabled = !enabled || !editor.value.trim();
|
|
const prompt = $('#chat-start-prompt');
|
|
if (prompt) {
|
|
prompt.hidden = !enabled || Boolean(chat?.messages.length) || Boolean(editor.value);
|
|
prompt.lastElementChild.textContent = t('chat.input.start_conversation');
|
|
}
|
|
for (const button of document.querySelectorAll('#chat-format-bar button, #chat-emoji, #chat-attach')) button.disabled = !enabled;
|
|
const attachment = $('#chat-attach');
|
|
if (attachment) attachment.hidden = !canAttachFiles(chat?.state.conn);
|
|
const toolbar = $('#chat-format-bar');
|
|
if (toolbar) toolbar.hidden = S.prefs?.chatToolbarVisibility === 'inactive' || (S.prefs?.chatToolbarVisibility === 'dynamic' && !$('#chat-form').contains(document.activeElement));
|
|
editor.placeholder = !enabled ? t('ui.not.connected') : t('chat.sendMessage');
|
|
editor.setAttribute('aria-label', t('ui.message'));
|
|
}
|
|
export function onSnapshot(conn) {
|
|
const state = stateFor(conn); if (!state) return;
|
|
void restore(state);
|
|
// A chat kept out of the sidebar (openIncomingChats off) is opened from its client in the tree; once that client
|
|
// has left, the sidebar list is the only way left to read its unread messages.
|
|
for (const chat of state.chats.values()) {
|
|
if (chat.kind === 'client' && chat.hidden && chat.unread > 0 && !partner(chat)) revealChat(chat);
|
|
}
|
|
if (viewedConnection() === conn) {
|
|
if (displayed !== current()) onViewChanged();
|
|
else { renderTabs(); if (displayed && !displayed.loaded) void loadPage(displayed); }
|
|
}
|
|
}
|
|
export function onViewChanged() {
|
|
const next = current();
|
|
if (displayed !== next) closeComposer();
|
|
if (displayed && editor) displayed.draft = editor.value;
|
|
// Only a different conversation replaces the document and clears undo/selection; re-rendering the same
|
|
// conversation keeps the live editor state.
|
|
const changed = displayed !== next;
|
|
displayed = next;
|
|
if (editor && changed) editor.reset(next?.draft ?? '');
|
|
if (displayed && S.view === 'main') displayed.unread = 0;
|
|
renderTabs(); renderLog(); badge();
|
|
if (displayed && !displayed.loaded) void loadPage(displayed);
|
|
}
|
|
export function onConnectionClosed(conn) {
|
|
// Unread chats that were kept out of the sidebar reopen with the next session instead of being lost.
|
|
for (const chat of states.get(conn)?.chats.values() ?? []) if (chat.kind === 'client' && chat.hidden && chat.unread > 0) persistOpen(chat, true);
|
|
states.delete(conn); onViewChanged();
|
|
}
|
|
/** Unread private messages from client `uid` on `conn` (tree highlight while openIncomingChats is off). */
|
|
export function privateUnread(conn, uid) { return states.get(conn)?.chats.get(`client:${uid}`)?.unread ?? 0; }
|
|
export function isClientIgnored(conn, clientId) { return isIgnoredUid(S.prefs, clientById(clientId, conn)?.uid); }
|
|
/** Client-menu "Ignore User": adds or removes the client's UID; own client and UID-less clients are refused. */
|
|
export async function setClientIgnored(conn, clientId, ignored) {
|
|
const client = clientById(clientId, conn);
|
|
if (!client?.uid || client.id === conn?.snap?.own_client_id) throw new Error('This client cannot be ignored');
|
|
await setIgnoredUser(client.uid, client.nickname, ignored);
|
|
}
|
|
export function unreadCount(conn) { let count = 0; for (const chat of states.get(conn)?.chats.values() ?? []) count += chat.unread; return count; }
|
|
function badge() {
|
|
let count = 0; for (const conn of states.keys()) count += unreadCount(conn);
|
|
count = Math.min(count, 1_000_000); if (count === lastBadge) return; lastBadge = count;
|
|
const canvas = document.createElement('canvas'); canvas.width = 32; canvas.height = 32;
|
|
const ctx = canvas.getContext('2d'); ctx.fillStyle = '#CC3838'; ctx.beginPath(); ctx.arc(16, 16, 16, 0, Math.PI * 2); ctx.fill();
|
|
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = 'bold 18px sans-serif'; ctx.fillText(count > 99 ? '99+' : String(count), 16, 17);
|
|
tp.setUnreadBadge(count, count ? canvas.toDataURL('image/png') : null).catch(report);
|
|
emit('chat-unread');
|
|
}
|
|
async function attach() {
|
|
const chat = current(); if (!canSend(chat)) return;
|
|
const conn = chat.state.conn; const session = conn.session;
|
|
const channelId = conn.snap.own_channel_id; const serverUid = conn.snap.server.uid; const address = conn.conn.address;
|
|
try {
|
|
const files = await chooseAndUploadChatAttachments(conn.id, channelId);
|
|
if (!isAlive(conn) || conn.session !== session || states.get(conn) !== chat.state || chat.state.chats.get(chat.key) !== chat) return;
|
|
const endpoint = new URL(`ts3://${address}`);
|
|
for (const file of files) {
|
|
const query = new URLSearchParams({ port: endpoint.port || '9987', serverUID: serverUid, channel: String(file.channelId), path: file.path, filename: file.name, size: String(file.size), isDir: '0' });
|
|
chat.draft += `${chat.draft ? '\n' : ''}ts3file://${endpoint.hostname}?${query}`;
|
|
}
|
|
if (current() === chat) { editor.value = chat.draft; updateComposer(); }
|
|
} catch (err) { report(err); }
|
|
}
|