vybe/client/message.js

81 lines
2.2 KiB
JavaScript

import { render, html } from '/uhtml.js';
let msg;
function sendMessage(e) {
e.preventDefault();
if (!msg.value)
return;
window.emit('send_message', {
message: msg.value,
thread: window.currentThread.id
});
msg.value = '';
}
let earliestMessage;
window.socket.on('new_message', message => {
if (message.thread !== window.currentThread.id)
return;
const messages = document.getElementById('messages');
let scroll = messages.scrollHeight - messages.scrollTop <= messages.clientHeight;
messages.appendChild(html.node`
<div class='message'>
<strong>${message.name}: </strong>
${message.message}
</div>`);
if (scroll)
messages.scroll(0, messages.scrollHeight - messages.clientHeight);
if (!earliestMessage)
earliestMessage = message.id;
});
function loadMessages() {
if (!msg) {
render(document.getElementById('message'), html`
<button id='loadmore' class='hidden' onclick=${loadMessages}>
load more messages
</button>
<div id='messages'></div>
<form id='msginput' onsubmit=${sendMessage}>
<input id='msg' placeholder='write a message...' />
<button type='submit' id='sendmsg'>send</button>
</form>
`);
msg = document.getElementById('msg');
}
const messages = document.getElementById('messages');
if (!this) { // called from chooseThread, initializing thread
messages.innerHTML = '';
earliestMessage = null;
}
window.emit(
'get_history',
{
before: earliestMessage,
thread: window.currentThread.id
},
msg => {
if (!msg.success)
console.log('get_history failed: ' + msg.message);
if (msg.messages.length > 0) {
earliestMessage = msg.messages[msg.messages.length - 1].id;
for (let message of msg.messages)
messages.prepend(html.node`
<div class='message'>
<strong>${message.name}: </strong>
${message.message}
</div>`);
}
if (msg.more)
document.getElementById('loadmore').classList.remove('hidden');
else
document.getElementById('loadmore').classList.add('hidden');
messages.scroll(0, messages.scrollHeight - messages.clientHeight);
}
);
}
export default loadMessages;