let tableKey = { name: "", passcode: "" } let table = null; let conn = null; let offline = false; let msgQ = []; const lagDiv = document.getElementById("lag"); const secondaryPreviewZone = document.getElementById("tokenPreview_alt"); const secondaryPreviewIdInput = document.getElementById("tokenPreview_alt_id"); const dismissPreviewBtn = document.getElementById("tokenPreview_alt_clear"); function showTableModal(show) { const modal = document.getElementById("table_modal"); if (modal) { modal.style.display = show ? "block" : "none"; } } function fmtLeading(n) { return n < 10 ? "0" + n : String(n); } function formatDice(r) { const date = new Date(r.timestamp) const p = document.createElement("p"); const month = date.getMonth() + 1; const day = date.getDate(); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); p.innerHTML = `${date.getFullYear()}-${fmtLeading(month)}-${fmtLeading(day)} ${fmtLeading(hours)}:${fmtLeading(minutes)}:${fmtLeading(seconds)} ${r.player} rolled ${r.roll.length}d${r.faces} ${(r.note ? "(" + r.note + ")" : "")}
[${r.roll}] (total ${r.roll.reduce((a,c)=>a+c,0)})`; return p; } function logDice(dice) { const diceLog = document.getElementById("dice_log"); if (!Array.isArray(dice)) { dice = [ dice ]; } else { if (diceLog) { diceLog.innerHTML = ""; } } if (diceLog) { for(const r of dice) { try{ const p = formatDice(r); diceLog.append(p); p.scrollIntoView(); } catch{} } } } function setAuxMsg(msg) { const auxDiv = document.getElementById("aux"); if (auxDiv) { auxDiv.innerText = msg; } } function updateTokens(tokens) { // update internal token array and map processTokens(tokens); // update token select window renderTokenSelect(); // if admin, update token master list renderTokenMasterList(); } function renderTokenSelect() { const tokenSelect = document.getElementById("token_select"); let tokenSelectHTML = ""; tokenSelect.innerHTML = tokenSelectHTML; } // the following few functions aren't socket related but they directly relate to the previous function function initSpritePreviewById(id) { const img = document.createElement("img"); const token = tokens.find(t=>t.t.id == id); if (token && id) { img.src = token.t.sprite; secondaryPreviewIdInput.value = id; img.onload = () => { scaleAltSpritePreview(); } } dismissPreviewBtn.style.display = (token && id) ? "block" : "none"; secondaryPreviewZone.innerHTML = ""; secondaryPreviewZone.appendChild(img); } function dismissPreview() { initSpritePreviewById(null); } function scaleAltSpritePreview() { if (mapImg && mapImg._image) { const id = secondaryPreviewIdInput.value; const scaleFactor = mapImg._image.clientWidth / mapImg._image.naturalWidth; const img = secondaryPreviewZone.children[0]; const token = tokens.find(t=>t.t.id == id); if (img && token) { img.width = token.t.w * scaleFactor; img.height = token.t.h * scaleFactor; } } } function makeUpToDate(table) { if (table) { // map image has to be set before tokens can be handled! if (table.mapImg) { setMapImg(table.mapImg); } if (table.auxMsg) { setAuxMsg(table.auxMsg); } if (table.diceRolls) { logDice(table.diceRolls); } else if (table.diceRoll) { logDice(table.diceRoll); } if (table.tokens) { updateTokens(table.tokens); } else if (table.token) { updateTokens([table.token]); } } } function setMapImg(url) { initializeMap(url); } function isTableKeyValid(name, passcode) { const r = /^[a-zA-Z0-9_]+$/; return r.test(name) && r.test(passcode); } function leave() { conn.close(1000); } function dial() { // get tableKey from UI const tblNameInput = document.getElementById("input_table_name"); const tblPassInput = document.getElementById("input_table_pass"); const joinTblBtn = document.getElementById("table_join"); const leaveTblBtn = document.getElementById("table_leave"); if (tblNameInput && tblPassInput && tblNameInput.value && tblPassInput.value) { if (isTableKeyValid(tblNameInput.value, tblPassInput.value)) { tableKey.name = tblNameInput.value; tableKey.passcode = tblPassInput.value; if (conn) { conn.close(1000); } const wsProto = location.protocol == "https:" ? "wss" : "ws"; conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, `${tableKey.name}.${tableKey.passcode}`); conn.addEventListener("close", e => { offline = true; if (e.code == 1006 && e.wasClean) { setErr("Table not found - check the name and passcode are correct"); } else if (e.code > 1001) { lagDiv.style.display = "block"; setTimeout(dial, 1000) } else { tblNameInput.readOnly = false; tblPassInput.readOnly = false; joinTblBtn.style.display = adminToken ? "none" : "inline"; leaveTblBtn.style.display = "none"; tabletop = document.getElementById("tabletop"); if (tabletop) { tabletop.style.display = "none"; } table = null; while (tokens.some(t=>t)) { tokens[0].m.removeFrom(map); tokens.shift(); } mapImg.removeFrom(map); mapImg = null; } }); conn.addEventListener("open", e => { offline = false; tblNameInput.readOnly = true; tblPassInput.readOnly = true; joinTblBtn.style.display = "none"; leaveTblBtn.style.display = adminToken ? "none" : "inline"; lagDiv.style.display = "none"; let m = null; while (m = msgQ.shift()) { if (m) { publish(m); } } closeErr(); tabletop = document.getElementById("tabletop"); if (tabletop) { tabletop.style.display = "block"; } }); conn.addEventListener("error", e => { setErr(`Websocket error`); conn.close(3000); }) conn.addEventListener("message", e => { const data = JSON.parse(e.data); if (table == null) { table = data; } if (data.diceRolls) { // dicerolls are treated as a byte array when marshalling to json, so we have to decode them data.diceRolls.forEach(r=>{ r.roll = Uint8Array.from(atob(r.roll), c => c.charCodeAt(0)) }) makeUpToDate(table); } else { if (data.diceRoll) { data.diceRoll.roll = Uint8Array.from(atob(data.diceRoll.roll), c => c.charCodeAt(0)); } makeUpToDate(data); } console.log(data); }); } else { setErr("Table name and passcode can only be alphanumeric and underscores"); } }else { setErr("Table name and passcode required"); } } async function publish(msg) { if (offline) { msgQ.push(msg); } else { msg.key = tableKey; const res = await fetch('/publish', { method: 'POST', body: JSON.stringify(msg) }); if (!res.ok) { setErr("Failed to publish message"); } } }