StockAnalysis / static /js /lobby.js
igardner's picture
fix: reset corrupt sqlite and reduce lobby load
626842d
Raw History Blame Contribute Delete
14.2 kB
/* Shared matchmaking lobby: HTTP is authoritative, WebSocket is an accelerator. */
(function () {
const queueCount = document.getElementById('queue-count');
const queueMessage = document.getElementById('queue-message');
const leaveButton = document.getElementById('leave-queue-button');
const resumeButton = document.getElementById('resume-queue-button');
const readyCount = document.getElementById('ready-count');
const connectionLabel = document.getElementById('connection-label');
const prompt = document.getElementById('round-prompt');
const options = document.getElementById('round-options');
const roundClock = document.getElementById('round-clock');
const roundStatus = document.getElementById('round-status');
const chat = document.getElementById('lobby-chat');
const chatForm = document.getElementById('lobby-chat-form');
const chatInput = document.getElementById('lobby-chat-input');
const chatStatus = document.getElementById('lobby-chat-status');
const participationCard = document.getElementById('participation-card');
const participationPrompt = document.getElementById('participation-title');
const participationForm = document.getElementById('participation-form');
const participationAnswer = document.getElementById('participation-answer');
const participationSubmit = document.getElementById('participation-submit');
const participationFeedback = document.getElementById('participation-feedback');
if (!queueCount || !chat) return;
let currentRound = null;
let lastMessageId = 0;
let retry = 0;
let socket = null;
let queueActionPending = false;
const seen = new Set();
async function api(url, options) {
const response = await fetch(url, Object.assign({ credentials: 'same-origin' }, options || {}));
const body = await response.json().catch(function () { return {}; });
if (!response.ok || body.ok === false) {
throw new Error(body.error || ('Request failed (' + response.status + ')'));
}
return body;
}
function setConnection(state) {
if (connectionLabel) connectionLabel.textContent = state;
const pill = document.getElementById('lobby-connection');
if (pill) {
pill.classList.toggle('offline', state === 'offline');
pill.classList.toggle('connecting', state === 'connecting');
pill.classList.toggle('polling', state === 'polling');
}
}
function redirectToMatch(match) {
if (!match || !match.url) return;
if (window.ParlorMotion && typeof window.ParlorMotion.enterRoom === 'function') {
window.ParlorMotion.enterRoom(match.url);
} else {
location.assign(match.url);
}
}
function updateQueue(data) {
queueCount.textContent = String(data.queue_count == null ? 0 : data.queue_count);
if (readyCount) readyCount.textContent = String(data.ready_count == null ? 0 : data.ready_count);
const min = document.getElementById('matchmaking-min-players');
if (min && data.min_players) min.textContent = String(data.min_players);
leaveButton.hidden = !data.queued;
if (resumeButton) resumeButton.hidden = data.queue_status !== 'paused';
if (participationCard) {
const promptState = data.participation_prompt;
participationCard.hidden = !promptState || promptState.complete || !data.queued;
if (promptState && participationPrompt) {
participationPrompt.textContent = promptState.prompt;
if (participationAnswer) participationAnswer.dataset.promptId = promptState.id;
}
}
if (!data.onboarding_complete) {
queueMessage.textContent = 'The parlor will ask a few questions before it finds your table. You can skip them.';
} else if (data.queue_status === 'paused') {
queueMessage.textContent = 'You stepped away from the queue. The conversation is still open.';
} else if (data.queued && !data.participated) {
queueMessage.textContent = 'You’re in the parlor. Answer the question or send a message; the table forms after guests speak.';
} else if (data.queued) {
const position = data.queue_position ? ' · place ' + data.queue_position : '';
queueMessage.textContent = 'You’ve spoken.' + position + ' The parlor is gathering the rest of your table.';
} else {
queueMessage.textContent = 'The parlor is preparing your seat…';
}
redirectToMatch(data.match);
}
function renderRound(round) {
if (!round || !prompt || !options) return;
currentRound = round;
prompt.textContent = round.prompt;
roundClock.textContent = round.status === 'reveal' ? 'The reveal' : 'Round in progress';
options.replaceChildren();
(round.options || []).forEach(function (choice) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'choice-button';
button.textContent = choice;
button.disabled = round.status !== 'open';
button.setAttribute('aria-pressed', String(round.my_vote === choice));
if (round.my_vote === choice) button.classList.add('selected');
button.addEventListener('click', function () { vote(round.id, choice); });
options.appendChild(button);
if (round.status === 'reveal') {
const tally = document.createElement('span');
tally.className = 'choice-tally';
tally.textContent = String((round.votes || {})[choice] || 0);
button.appendChild(tally);
}
});
roundStatus.textContent = round.status === 'reveal'
? 'The round is complete. Results are shown; the next question is on its way.'
: (round.my_vote ? 'Vote recorded. You can change it until the round ends.' : 'Pick one answer. Votes stay private until the reveal.');
updateRoundClock();
}
function updateRoundClock() {
if (!currentRound || !roundClock) return;
if (currentRound.status === 'reveal') {
roundClock.textContent = 'The reveal';
return;
}
const end = Date.parse(currentRound.ends_at);
const seconds = Math.max(0, Math.ceil((end - Date.now()) / 1000));
roundClock.textContent = seconds ? seconds + 's left' : 'Revealing…';
}
async function vote(roundId, choice) {
try {
const response = await api('/api/lobby/minigame/' + roundId + '/vote', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ choice: choice }),
});
renderRound(response.data.round);
} catch (error) {
roundStatus.textContent = error.message;
refreshState();
}
}
function appendMessage(message) {
if (!message || !message.id || seen.has(message.id)) return;
seen.add(message.id);
if (seen.size > 500) seen.delete(seen.values().next().value);
lastMessageId = Math.max(lastMessageId, Number(message.id));
const empty = document.getElementById('lobby-chat-empty');
if (empty) empty.remove();
const row = document.createElement('div');
row.className = 'msg';
if (message.source && message.source !== 'user') row.classList.add('system');
if (message.avatar) {
const avatar = document.createElement('img');
avatar.className = 'avatar avatar-sm';
avatar.src = message.avatar;
avatar.alt = '';
row.appendChild(avatar);
}
const body = document.createElement('div');
body.className = 'body';
const top = document.createElement('div');
top.className = 'top';
const who = document.createElement('span');
who.className = 'who';
who.textContent = message.user || 'Guest';
top.appendChild(who);
if (message.is_simulated) top.appendChild(el('span', 'badge badge-sim', 'SIM'));
if (message.at) {
const at = document.createElement('span');
at.className = 'at';
at.textContent = message.at;
top.appendChild(at);
}
const text = document.createElement('div');
text.className = 'text';
text.textContent = message.msg || '';
body.appendChild(top);
body.appendChild(text);
row.appendChild(body);
chat.appendChild(row);
while (chat.children.length > 200) chat.firstElementChild.remove();
chat.scrollTop = chat.scrollHeight;
}
async function refreshState() {
if (document.hidden) return;
try {
const response = await api('/api/lobby/state');
updateQueue(response.data);
renderRound(response.data.round);
(response.data.messages || []).forEach(appendMessage);
if (socket && socket.readyState === WebSocket.OPEN) setConnection('live');
else if (socket && socket.readyState === WebSocket.CONNECTING) setConnection('connecting');
else setConnection('polling');
} catch (error) {
queueMessage.textContent = 'The parlor is temporarily unreachable. Retrying…';
setConnection('offline');
}
}
async function refreshMessages() {
if (document.hidden || (socket && socket.readyState === WebSocket.OPEN)) return;
try {
const response = await api('/api/lobby/chat?after=' + lastMessageId);
(response.data.messages || []).forEach(appendMessage);
} catch (error) { /* next poll or WebSocket will recover */ }
}
leaveButton.addEventListener('click', async function () {
if (queueActionPending) return;
queueActionPending = true;
leaveButton.disabled = true;
try {
await api('/api/matchmaking/queue', { method: 'DELETE' });
await refreshState();
} catch (error) {
queueMessage.textContent = 'Could not leave the queue: ' + error.message;
} finally {
queueActionPending = false;
leaveButton.disabled = false;
}
});
if (resumeButton) resumeButton.addEventListener('click', async function () {
if (queueActionPending) return;
queueActionPending = true;
resumeButton.disabled = true;
try {
const response = await api('/api/matchmaking/queue', { method: 'POST' });
updateQueue(response.data);
} catch (error) {
queueMessage.textContent = 'Could not return to the queue: ' + error.message;
} finally {
queueActionPending = false;
resumeButton.disabled = false;
}
});
if (participationForm) participationForm.addEventListener('submit', async function (event) {
event.preventDefault();
if (queueActionPending) return;
const answer = participationAnswer.value.trim();
if (!answer) return;
queueActionPending = true;
participationSubmit.disabled = true;
participationFeedback.textContent = 'The room heard you. Finding your table…';
try {
const response = await api('/api/lobby/answer', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt_id: participationAnswer.dataset.promptId, answer: answer }),
});
appendMessage(response.data.message);
participationAnswer.value = '';
updateQueue(response.data.lobby);
await refreshState();
} catch (error) {
participationFeedback.textContent = 'The parlor could not record that: ' + error.message;
} finally {
queueActionPending = false;
participationSubmit.disabled = false;
}
});
document.addEventListener('parlor:onboarding-complete', refreshState);
chatForm.addEventListener('submit', async function (event) {
event.preventDefault();
const msg = chatInput.value.trim();
if (!msg) return;
const button = chatForm.querySelector('button[type="submit"]');
button.disabled = true;
chatStatus.textContent = 'Sending…';
try {
const response = await api('/api/lobby/chat', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ msg: msg }),
});
appendMessage(response.data.message);
chatInput.value = '';
const participation = response.data.message.matchmaking || {};
if (participation.qualified) {
chatStatus.textContent = 'Message sent. Your chat counts toward matchmaking.';
} else if (participation.minimum_words) {
chatStatus.textContent = 'Message sent. Use at least ' + participation.minimum_words + ' words to count toward matchmaking.';
} else {
chatStatus.textContent = 'Message sent.';
}
} catch (error) {
chatStatus.textContent = 'Message not sent: ' + error.message;
} finally {
button.disabled = false;
chatInput.focus();
}
});
function connect() {
const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:';
try {
socket = new WebSocket(scheme + '//' + location.host + '/ws/lobby');
} catch (error) {
setConnection('polling');
retry += 1;
window.setTimeout(connect, Math.min(1000 * Math.pow(2, Math.min(retry, 5)), 20000));
return;
}
socket.onopen = function () { retry = 0; setConnection('live'); refreshState(); };
socket.onmessage = function (event) {
let packet;
try { packet = JSON.parse(event.data); } catch (error) { return; }
const data = packet.data || {};
if (packet.type === 'chat.message') appendMessage(data);
else if (packet.type === 'queue.updated') {
queueCount.textContent = String(data.queue_count || 0);
if (readyCount) readyCount.textContent = String(data.ready_count || 0);
} else if (packet.type === 'match.created' && Number(data.user_id) === Number(window.LOBBY_USER_ID)) {
redirectToMatch(data);
} else if (packet.type.indexOf('minigame.') === 0) {
renderRound(data);
}
};
socket.onclose = function () {
setConnection('polling');
retry += 1;
window.setTimeout(connect, Math.min(1000 * Math.pow(2, Math.min(retry, 5)), 20000));
};
socket.onerror = function () { setConnection('offline'); };
}
window.setInterval(updateRoundClock, 1000);
window.setInterval(function () {
if (!document.hidden && (!socket || socket.readyState !== WebSocket.OPEN)) refreshState();
}, 30000);
window.setInterval(refreshMessages, 15000);
document.addEventListener('visibilitychange', function () {
if (!document.hidden && (!socket || socket.readyState !== WebSocket.OPEN)) {
refreshState();
refreshMessages();
}
});
refreshState();
connect();
})();