import { render, html } from '/uhtml.js'; let msg; function sendMessage(event) { event.preventDefault(); if (!msg.value) return; window.currentInstance.emit('send_message', { message: msg.value, thread: window.currentThread.id }); msg.value = ''; } let earliestMessage; function loadMessages(callback) { let instance = window.currentInstance; if (!msg) { render(document.getElementById('message'), html`
`); msg = document.getElementById('msg'); } const messages = document.getElementById('messages'); if (!this) { // called from chooseThread, initializing thread messages.innerHTML = ''; earliestMessage = null; if (window.currentThread.permissions.post) document.getElementById('msginput').classList.remove('hidden'); else document.getElementById('msginput').classList.add('hidden'); } instance.emit('get_history', { before: earliestMessage, thread: window.currentThread.id }, async msg => { if (!msg.success) { console.log('get_history failed: ' + msg.message); return; } callback && callback(msg.messages); if (msg.messages.length > 0) { earliestMessage = msg.messages[msg.messages.length - 1].id; let users = {}; for (let message of msg.messages) { let user; if (message.user.name) user = message.user; else { user = users[message.user.id]; if (user === undefined) try { user = users[message.user.id] = await window.getUser(message.user.id); } catch (e) { console.log(`error getting user ${message.user.id}:`, e); users[message.user.id] = false; } if (user) { user.id = message.user.id; user.permissions = message.user.permissions; } } let div = html.node`
: ${message.content}
`; div.prepend(user ? window.makeUser(user, user.id.split?.('@')[1] || instance.url) : html.node`${message.user.id}`); messages.prepend(div); } } if (msg.more) document.getElementById('loadmore').classList.remove('hidden'); else document.getElementById('loadmore').classList.add('hidden'); messages.scroll(0, messages.scrollHeight - messages.clientHeight); }); if (!instance.messaged) { instance.socket.on('new_message', message => { if (message.thread !== window.currentThread?.id || instance !== window.currentInstance) return; const messages = document.getElementById('messages'); let scroll = messages.scrollTop + 10 >= messages.scrollHeight - messages.clientHeight; let div = html.node`
: ${message.content}
`; div.prepend(window.makeUser(message.user, message.user.id.split?.('@')[1] || instance.url)); messages.append(div); if (scroll) messages.scroll(0, messages.scrollHeight - messages.clientHeight); if (!earliestMessage) earliestMessage = message.id; }); instance.messaged = true; } } export default loadMessages;