StockAnalysis / static /js /room.js
igardner's picture
fix: reset corrupt sqlite and reduce lobby load
626842d
Raw History Blame Contribute Delete
6.01 kB
/* Room chat: HTTP writes are canonical; WebSocket and polling deliver updates. */
(function () {
const roomId = window.ROOM_ID;
const chat = document.getElementById('chat');
const form = document.getElementById('chat-form');
const input = document.getElementById('chat-input');
const feedback = document.getElementById('chat-feedback');
if (!chat || !form || !input || !roomId) return;
let lastId = 0;
let wsRetry = 0;
let ws = null;
window.ROOM_WS_CONNECTED = false;
const seen = new Set();
chat.querySelectorAll('.msg[data-id]').forEach(function (node) {
const id = Number(node.dataset.id);
if (id) {
seen.add(id);
if (seen.size > 500) seen.delete(seen.values().next().value);
lastId = Math.max(lastId, id);
}
});
function setConnection(state) {
window.ROOM_WS_CONNECTED = state === 'live';
const label = document.getElementById('room-connection-label');
const pill = document.getElementById('room-connection');
if (label) label.textContent = state;
if (pill) {
pill.classList.toggle('offline', state === 'offline');
pill.classList.toggle('connecting', state === 'connecting');
pill.classList.toggle('polling', state === 'polling');
pill.classList.toggle('readonly', state === 'read only');
}
}
function node(tag, className, text) {
const el = document.createElement(tag);
if (className) el.className = className;
if (text != null) el.textContent = text;
return el;
}
function appendMessage(message) {
const id = Number(message.id || 0);
if (id && seen.has(id)) return;
if (id) { seen.add(id); lastId = Math.max(lastId, id); }
const empty = document.getElementById('chat-empty');
if (empty) empty.remove();
const wrap = node('div', 'msg');
if (message.is_system) wrap.classList.add('system');
else if (message.is_you) wrap.classList.add('you');
if (id) wrap.dataset.id = String(id);
if (!message.is_system && message.avatar) {
const image = node('img', 'avatar avatar-sm');
image.src = message.avatar;
image.alt = '';
image.onerror = function () { image.hidden = true; };
wrap.appendChild(image);
}
const body = node('div', 'body');
if (!message.is_system) {
const top = node('div', 'top');
top.appendChild(node('span', 'who', message.user || ''));
if (message.is_simulated) top.appendChild(node('span', 'badge badge-sim', 'SIM'));
if (message.at) top.appendChild(node('span', 'at', message.at));
body.appendChild(top);
}
body.appendChild(node('div', 'text', message.msg || ''));
wrap.appendChild(body);
chat.appendChild(wrap);
while (chat.children.length > 200) chat.firstElementChild.remove();
chat.scrollTop = chat.scrollHeight;
}
async function poll() {
if (document.hidden || (ws && ws.readyState === WebSocket.OPEN)) return;
try {
const response = await fetch('/api/room/' + roomId + '/messages?after=' + lastId, { credentials: 'same-origin' });
if (!response.ok) {
if (window.ROOM_MEMBER !== false && (!ws || ws.readyState !== WebSocket.OPEN)) setConnection('offline');
return;
}
const data = await response.json();
(data.messages || []).forEach(appendMessage);
if (window.ROOM_MEMBER !== false && (!ws || ws.readyState !== WebSocket.OPEN)) setConnection('polling');
} catch (error) {
if (window.ROOM_MEMBER !== false && (!ws || ws.readyState !== WebSocket.OPEN)) setConnection('offline');
}
}
form.addEventListener('submit', async function (event) {
event.preventDefault();
const message = input.value.trim();
if (!message) return;
const button = form.querySelector('button[type="submit"]');
button.disabled = true;
feedback.textContent = 'Sending…';
try {
const response = await fetch('/api/room/' + roomId + '/chat', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ msg: message }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Message was not accepted');
appendMessage({ id: data.id, user: data.user, msg: data.msg, at: data.at, is_you: true, avatar: window.__meAvatar || null });
input.value = '';
feedback.textContent = 'Message sent.';
} catch (error) {
feedback.textContent = 'Message not sent: ' + error.message;
} finally {
button.disabled = false;
input.focus();
}
});
function connect() {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
try { ws = new WebSocket(protocol + '//' + location.host + '/ws/room/' + roomId); }
catch (error) {
setConnection('polling');
wsRetry += 1;
window.setTimeout(connect, Math.min(1000 * Math.pow(2, Math.min(wsRetry, 5)), 20000));
return;
}
ws.onopen = function () { wsRetry = 0; setConnection('live'); };
ws.onmessage = function (event) {
let data;
try { data = JSON.parse(event.data); } catch (error) { return; }
if (data.type === 'chat') appendMessage(data);
else if (data.type === 'system') appendMessage({ is_system: true, msg: data.msg });
else if (data.type === 'game.updated') {
document.dispatchEvent(new CustomEvent('room:game-updated', { detail: data }));
}
};
ws.onclose = function () {
setConnection('polling');
wsRetry += 1;
window.setTimeout(connect, Math.min(1000 * Math.pow(2, Math.min(wsRetry, 5)), 20000));
};
ws.onerror = function () { setConnection('polling'); };
}
chat.scrollTop = chat.scrollHeight;
if (window.ROOM_MEMBER !== false) connect();
else setConnection('read only');
poll();
window.setInterval(poll, 15000);
document.addEventListener('visibilitychange', function () {
if (!document.hidden && (!ws || ws.readyState !== WebSocket.OPEN)) poll();
});
})();