vybe/client/message.js

76 lines
1.9 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.threadId
});
msg.value = '';
}
let earliestMessage;
window.socket.on('new_message', message => {
if (message.thread !== window.threadId)
return;
document.getElementById('messages').appendChild(html.node`
<div class='message'>
<strong>${message.name}: </strong>
${message.message}
</div>`);
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.threadId
},
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.add('hidden');
else
document.getElementById('loadmore').classList.remove('hidden');
}
);
}
export default loadMessages;