Titivillus/quest/static/quest.js

54 lines
2.1 KiB
JavaScript

var socket = new WebSocket('wss://' + document.domain + SCRIPT_NAME + '/ws/quest/' + quest_id + '/');
socket.oldSend = socket.send;
socket.send = function(event_title, data) {
data = JSON.stringify({event: event_title, data: data});
socket.oldSend.apply(this, [data]);
}
socket.events = {};
socket.onmessage = function(e) {
let data = JSON.parse(e.data);
let event = data.event;
data = data.data;
if (socket.events[event] === undefined) { return; }
socket.events[event](data);
}
socket.events['message'] = function(data) {
let msg_str = '<div id="message-' + data.message_id + '" class="message">';
msg_str = '<div class="messageHeader"><span class="messageName">' + data.name + '</span> ';
msg_str += '<span class="messageDate">' + strftime(data.date) + '</span> ';
msg_str += '<span class="messageID">No.<a href="javascript:quote(' + data.message_id + ')">' + data.message_id + '</a></span></div>';
msg_str += '<div class="messageContent">' + data.message + '</div></div><hr>';
let mbox = document.getElementById('chatWindow');
mbox.innerHTML = mbox.innerHTML + msg_str;
if ((mbox.scrollTop + mbox.offsetHeight) >= (mbox.scrollHeight - mbox.clientHeight / 2)) {
mbox.scrollTop = mbox.scrollHeight;
}
}
function padToTwo(number) {
if (number<=99) { number = ("0"+number).slice(-2); }
return number;
}
function strftime(date) {
date = new Date(date * 1000);
let date_str = date.getFullYear() + '-' + padToTwo(date.getMonth()+1) + '-' + padToTwo(date.getDate()) + ' ';
date_str += padToTwo(date.getHours()) + ':' + padToTwo(date.getMinutes()) + ':' + padToTwo(date.getSeconds());
return date_str;
}
function load() {
document.getElementById('chatWindow').scrollTop = document.getElementById('chatWindow').scrollHeight;
let mtarea = document.getElementById('messageTextArea');
mtarea.addEventListener('keypress', function(event) {
if (event.key == 'Enter' && !event.shiftKey) {
let text = mtarea.value.trim();
mtarea.value = '';
if (text == '') { return; }
document.getElementById('chatWindow').scrollTop = document.getElementById('chatWindow').scrollHeight;
socket.send('message', {message: text, quest_id: quest_id});
}
});
}