Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
The page's queue, join and chat script lives in src/ui/lobby-panel.js - no behaviour change #117
smith/arm:smith/95-the-page-s-queue-join-and-chat-script-li → main 1 commit fork
4 files
changed +315
−262
Software/so101/src/server.test.ts +2 −2
| @@ -147,7 +147,7 @@ describe("viewer page", () => { | ||
| 147 | 147 | expect(html).toContain('$("events").replaceChildren('); |
| 148 | 148 | }); |
| 149 | 149 | |
| 150 | test("a first visit downloads under 50 KB gzipped: the page and the modules it imports up front; the rest comes when needed", async () => { | |
| 150 | test("a first visit downloads under 52 KB gzipped: the page and the modules it imports up front; the rest comes when needed", async () => { | |
| 151 | 151 | const page = await (await fetch(`${base}/`)).text(); |
| 152 | 152 | const script = page.slice(page.indexOf('<script type="module">')); |
| 153 | 153 | const upfront = new Set([...page.matchAll(/<link rel="modulepreload" href="([^"]+)">/g), ...script.matchAll(/^\s*import [^;]*? from "([^"]+)";/gm)].map((m) => m[1]!)); |
| @@ -158,7 +158,7 @@ describe("viewer page", () => { | ||
| 158 | 158 | expect(r.status).toBe(200); |
| 159 | 159 | bytes += gzipSync(Buffer.from(await r.arrayBuffer()), { level: 6 }).length; |
| 160 | 160 | } |
| 161 | expect(bytes).toBeLessThan(50_000); | |
| 161 | expect(bytes).toBeLessThan(52_000); // was 50_000: the room script is its own gzip stream now (+1.6 KB of per-file overhead, no new code) | |
| 162 | 162 | // three.js, the leader's mapping, the calibration panel and the Machine panel are imported where they are used, not up front. |
| 163 | 163 | for (const lazy of ["three", "/leader-map.js", "calibration.js", "reach.js", "machine-panel.js", "machine.js"]) expect([...upfront].some((p) => p === lazy || p.endsWith(`/${lazy}`))).toBe(false); |
| 164 | 164 | expect(script).toContain('import("/leader-map.js")'); |
Software/so101/src/ui/lobby-panel.js added +285
| @@ -0,0 +1,285 @@ | ||
| 1 | // @ts-nocheck: the page's queue, join and chat script, moved here as it was (it was never type-checked inside viewer.html); the pure helpers are covered by lobby-panel.test.ts | |
| 2 | /** | |
| 3 | * The room on the page: the turn, the queue, the join form and the chat, all over the one /live socket. Plain ESM, | |
| 4 | * served to the page at /ui/ and imported by viewer.html. The page hands in what it owns (its element lookup, tabs, | |
| 5 | * status handlers and the driving lock) and gets back the room's state and the few calls the rest of it needs. | |
| 6 | * Everything from the server goes in with textContent. | |
| 7 | */ | |
| 8 | ||
| 9 | /** Whole minutes, at least one, for a wait in ms. */ | |
| 10 | export const waitMinutes = (ms) => Math.max(1, Math.ceil(ms / 60000)); | |
| 11 | /** m:ss for a time left in ms. */ | |
| 12 | export const minutes = (ms) => { const t = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; }; | |
| 13 | export const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`; | |
| 14 | /** One line of the queue as plain text: the page puts each field in with textContent, so a name is never markup. */ | |
| 15 | export const queueRow = (x, me) => { | |
| 16 | const mine = Boolean(me && x.id === me.id); | |
| 17 | return { className: mine ? "me" : "", place: `${x.place}.`, name: mine ? `${x.name} (you)` : x.name, wait: `≤ ${waitMinutes(x.waitMs)} min` }; | |
| 18 | }; | |
| 19 | ||
| 20 | /** | |
| 21 | * @param {{ $: (id: string) => any, el: (tag: string, props?: object, ...children: any[]) => any, msg: (text: string, bad?: boolean) => void, | |
| 22 | * relayed: boolean, showTab: (name: string) => void, tab: () => string, applyStatus: (s: any) => void, noStatus: () => void, applyLock: () => void }} page | |
| 23 | */ | |
| 24 | export function createLobbyPanel({ $, el, msg, relayed, showTab, tab, applyStatus, noStatus, applyLock }) { | |
| 25 | // ---------------------------------------------------------------- the room: the turn, the queue and the chat over /live | |
| 26 | // Behind the hosted app's relay only the person whose turn it is may drive, and the server refuses everyone else. | |
| 27 | // The page follows suit: the Controls tab appears on your turn. Everything here arrives on one socket. | |
| 28 | let wordsSent = false; | |
| 29 | $("wordsForm").addEventListener("submit", (e) => { e.preventDefault(); wordsSent = true; say({ type: "words", words: $("wordsForm").elements.words.value.split(",").map((w) => w.trim()).filter(Boolean) }); }); | |
| 30 | const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false }; | |
| 31 | function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); } | |
| 32 | function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); } | |
| 33 | const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); }; | |
| 34 | const serverNow = () => Date.now() + lobby.offset; | |
| 35 | function tickClock() { | |
| 36 | const d = lobby.state?.driver, c = $("clock"), me = lobby.hello?.you; | |
| 37 | if (!relayed) return void (c.textContent = "On this machine: no sign-in, every visitor drives."); | |
| 38 | if (!lobby.state || !lobby.hello?.signin) return void (c.textContent = lobby.hello && !lobby.hello.signin ? "Local: no sign-in, every visitor drives." : ""); | |
| 39 | const mine = me ? lobby.state.queue.find((x) => x.id === me.id) : null; | |
| 40 | const place = mine ? ` · you're ${ordinal(mine.place)} in line, ≤ ${waitMinutes(mine.waitMs)} min` : ""; | |
| 41 | if (!d) $("ring").hidden = true; | |
| 42 | if (!d) { c.className = ""; c.textContent = lobby.state.paused ? `No new turns until the owner resumes${place || "; you can still join the line"}.` : "Free: take control to drive."; return; } | |
| 43 | const now = serverNow(), idle = d.idleEndsAt - now; | |
| 44 | const idleSoon = idle < 15000 && d.idleEndsAt < d.endsAt; | |
| 45 | c.className = idleSoon || d.readyBy ? "idle" : ""; | |
| 46 | tickRing(d, me, now); | |
| 47 | if (d.readyBy && me && d.id === me.id) return void (c.textContent = `Tap Ready within ${Math.max(0, Math.ceil((d.readyBy - now) / 1000))} s or the turn passes on`); | |
| 48 | c.textContent = idleSoon ? `Idle: the turn ends in ${Math.max(0, Math.ceil(idle / 1000))} s unless the arm moves` : `${minutes(d.endsAt - now)} left${place}`; | |
| 49 | } | |
| 50 | /** The ring is the driver's own: time left on the turn, in the seconds around it. */ | |
| 51 | function tickRing(d, me, now) { | |
| 52 | const ring = $("ring"), mine = Boolean(me && d.id === me.id), st = lobby.state; | |
| 53 | ring.hidden = !mine; | |
| 54 | if (!mine) return; | |
| 55 | const left = Math.max(0, d.endsAt - now); | |
| 56 | ring.style.setProperty("--p", `${Math.min(100, (left / Math.max(st.turnMs, 1)) * 100)}%`); | |
| 57 | ring.classList.toggle("low", left < 15000); | |
| 58 | $("ringN").textContent = left >= 60000 ? `${Math.ceil(left / 60000)}m` : `${Math.ceil(left / 1000)}`; | |
| 59 | } | |
| 60 | setInterval(tickClock, 250); | |
| 61 | $("quiet").onchange = (e) => { try { localStorage.setItem("so101.quiet", e.target.checked ? "1" : "0"); } catch {} }; | |
| 62 | /** "You're next": a tone and a buzz (Android) and an amber strip; no web push, so only while the page is open. */ | |
| 63 | let wasNext = false; | |
| 64 | const quiet = () => { try { return localStorage.getItem("so101.quiet") === "1"; } catch { return false; } }; | |
| 65 | function alertNext(next) { | |
| 66 | $("strip").classList.toggle("next", next); | |
| 67 | if (next && !wasNext) { | |
| 68 | navigator.vibrate?.([200, 100, 200]); | |
| 69 | if (!quiet()) try { | |
| 70 | const ctx = new (window.AudioContext || window.webkitAudioContext)(), o = ctx.createOscillator(), g = ctx.createGain(); | |
| 71 | o.frequency.value = 880; g.gain.value = 0.08; o.connect(g); g.connect(ctx.destination); o.start(); o.stop(ctx.currentTime + 0.25); o.onended = () => ctx.close(); | |
| 72 | } catch { /* autoplay refused: the amber strip is the alert */ } | |
| 73 | } | |
| 74 | wasNext = next; | |
| 75 | } | |
| 76 | const button = (textContent, className, onclick) => el("button", { textContent, className, type: "button", onclick }); | |
| 77 | /** The one thing to do about the turn, short enough for the strip. */ | |
| 78 | function turnButtons() { | |
| 79 | const st = lobby.state, me = lobby.hello?.you ?? null, d = st?.driver; | |
| 80 | if (!st || !lobby.hello?.signin) return []; // a run on one's own machine: everyone drives, nobody queues | |
| 81 | if (!me) return [button("Join to drive", "go", () => { showTab("queue"); $("joinName").focus(); })]; | |
| 82 | if (lobby.hello.banned) return []; // banned: watching only | |
| 83 | if (d?.id === me.id) return [...(d.readyBy ? [button("Ready", "go ready", () => say({ type: "ready" }))] : []), ...(!st.queue.length && !d.readyBy ? [button("+30 s", "", () => say({ type: "extend" }))] : []), button("Hand back", "", () => say({ type: "leave" }))]; | |
| 84 | if (st.queue.some((x) => x.id === me.id)) return [button("Leave", "", () => say({ type: "leave" }))]; | |
| 85 | return [button(me.owner && d ? "Take over" : d || (st.paused && !me.owner) ? "Join queue" : "Take control", "go", () => say({ type: "join" }))]; | |
| 86 | } | |
| 87 | function renderTurn() { | |
| 88 | const st = lobby.state, me = lobby.hello?.you ?? null; | |
| 89 | if (!st || !lobby.hello) return; | |
| 90 | const d = st.driver; | |
| 91 | $("driverLine").className = st.paused ? "paused" : d ? "" : "none"; | |
| 92 | const mine = me ? st.queue.find((x) => x.id === me.id) : null, driving = Boolean(me && d?.id === me.id); | |
| 93 | // The strip in words: watching, queued, next, your turn. | |
| 94 | const wait = waitMinutes(st.queue.length ? st.queue.at(-1).waitMs + st.turnMs : d ? Math.max(0, d.endsAt - st.now) : 0); | |
| 95 | $("driverLine").textContent = (st.paused ? "Paused for maintenance" + (d ? " · " : "") : "") + | |
| 96 | (driving ? (d.readyBy ? "Your turn · confirm you're here" : "Your turn") : mine ? (mine.place === 1 ? "You're next" : `#${mine.place} · ~${waitMinutes(mine.waitMs)} min`) : | |
| 97 | d ? (lobby.hello.signin && !lobby.hello.banned ? `Join queue · ${st.queue.length} waiting · ~${wait} min` : `${d.name} has control`) : st.paused ? "" : "Nobody has control"); | |
| 98 | $("driverTag").textContent = d ? `🎮 ${d.name}${driving ? " (you)" : ""}` : ""; | |
| 99 | $("strip").classList.toggle("ready", Boolean(driving && d.readyBy)); | |
| 100 | alertNext(Boolean(mine && mine.place === 1 && !st.paused)); | |
| 101 | $("notice").hidden = !st.announcement; | |
| 102 | $("notice").textContent = st.announcement ?? ""; | |
| 103 | $("capLine").textContent = st.maxSpeedPercent < 100 ? `Speed limited to ${st.maxSpeedPercent}% of full` : ""; | |
| 104 | $("turnActions").replaceChildren(...turnButtons()); | |
| 105 | $("quiet").checked = quiet(); | |
| 106 | $("queueActions").replaceChildren(el("span", { textContent: d ? (me && d.id === me.id ? "You" : d.name) : "Nobody", style: "flex:1;font-weight:600" }), ...turnButtons()); | |
| 107 | const joining = lobby.hello.signin && !me; | |
| 108 | $("joinForm").hidden = $("forgeSignin").hidden = !joining; | |
| 109 | if (!joining) $("joinErr").textContent = ""; | |
| 110 | $("forgeSignin").href = `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`; | |
| 111 | $("waiting").textContent = st.queue.length ? String(st.queue.length) : ""; | |
| 112 | $("queue").replaceChildren(...st.queue.map((x) => { | |
| 113 | const row = queueRow(x, me); | |
| 114 | const li = el("li", { className: row.className }, el("span", { className: "place", textContent: row.place }), el("span", { textContent: row.name }), el("span", { className: "wait", textContent: row.wait })); | |
| 115 | if (me?.owner) { const b = button("×", "x", () => say({ type: "end", id: x.id })); b.setAttribute("aria-label", `take ${x.name} out of the line`); li.append(b); } | |
| 116 | return li; | |
| 117 | })); | |
| 118 | $("modTurn").replaceChildren(...(me?.owner && d && d.id !== me.id ? [button(`End ${d.name}'s turn`, "danger", () => say({ type: "end", id: d.id }))] : [el("span", { className: "note", textContent: d ? "You are driving." : "Nobody is driving.", style: "color:var(--dim)" })])); | |
| 119 | if (me?.owner) { | |
| 120 | $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue"; | |
| 121 | $("pauseBtn").className = st.paused ? "go" : ""; | |
| 122 | $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused }); | |
| 123 | } | |
| 124 | $("mutedLine").replaceChildren(...(me?.owner ? lobby.mutedList.map((m) => el("div", { className: "item" }, el("span", { textContent: `${m.name} is muted` }), button("Unmute", "", () => say({ type: "mute", id: m.id, on: false })))) : [])); | |
| 125 | $("bannedLine").replaceChildren(...(me?.owner ? lobby.bannedList.map((b) => el("div", { className: "item" }, el("span", { textContent: `${b.name} is banned` }), button("Unban", "", () => say({ type: "ban", id: b.id, on: false })))) : [])); | |
| 126 | renderCrew(me); | |
| 127 | $("say").hidden = !me || lobby.hello.muted || lobby.hello.banned; | |
| 128 | $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Join (Queue tab) to chat." : lobby.hello.banned ? "You are banned: you can still watch." : lobby.hello.muted ? "The owner has muted you." : ""; | |
| 129 | chatBox.classList.toggle("moderated", Boolean(me?.owner)); | |
| 130 | tickClock(); | |
| 131 | applyLock(); | |
| 132 | } | |
| 133 | /** The owner's view of the crew moderator: on/off, the rules, lines it hid, people it suggests muting. */ | |
| 134 | function renderCrew(me) { | |
| 135 | const c = lobby.crew; | |
| 136 | const box = $("crewLine"); | |
| 137 | if (!me?.owner || !c?.settings) return box.replaceChildren(el("p", { textContent: me?.owner ? "Waiting for the moderator's settings." : "" })); | |
| 138 | if (box.contains(document.activeElement) && document.activeElement.matches("textarea, input")) return; // do not drop what is being typed | |
| 139 | const perMinute = el("input", { type: "number", min: 1, max: 600, step: 1, value: c.settings.maxPerMinute, id: "crewMax", inputMode: "numeric" }); | |
| 140 | const rules = el("textarea", { value: c.settings.rules, rows: 3, maxLength: 2000, ariaLabel: "Room rules for the crew moderator" }); | |
| 141 | const item = (text, ...buttons) => el("div", { className: "item" }, el("span", { textContent: text }), ...buttons); | |
| 142 | box.replaceChildren( | |
| 143 | item(c.available ? (c.settings.enabled ? "On: every chat line is checked." : "Off.") : "No model reachable: nothing is checked.", | |
| 144 | button(c.settings.enabled ? "Turn off" : "Turn on", "", () => say({ type: "crew", settings: { enabled: !c.settings.enabled } }))), | |
| 145 | el("div", { className: "item" }, el("label", { htmlFor: "crewMax", textContent: "Most lines checked per minute" }), perMinute, | |
| 146 | button("Save", "", () => say({ type: "crew", settings: { maxPerMinute: Number(perMinute.value) } }))), | |
| 147 | rules, el("div", { className: "row" }, button("Save rules", "", () => say({ type: "crew", settings: { rules: rules.value } }))), | |
| 148 | ...c.hidden.map((h) => item(`Hidden: ${h.message.from?.name}: ${h.message.text} (${h.reason})`, button("Restore", "", () => say({ type: "restore", id: h.message.id })))), | |
| 149 | ...c.suggestions.map((x) => item(`Suggests muting ${x.message.from?.name}: ${x.message.text} (${x.reason})`, button("Mute", "danger", () => say({ type: "mute", id: x.message.from.id, on: true })), button("Dismiss", "", () => say({ type: "dismiss", id: x.message.id }))))); | |
| 150 | } | |
| 151 | /** Join: one field, one button. The answer sets the session cookie; the room is reopened to hear who you are now. */ | |
| 152 | $("joinForm").onsubmit = async (e) => { | |
| 153 | e.preventDefault(); | |
| 154 | const button = $("joinForm").querySelector("button"), err = $("joinErr"); | |
| 155 | button.disabled = true; | |
| 156 | try { | |
| 157 | const r = await fetch("/join", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: $("joinName").value.trim() }) }); | |
| 158 | const body = await r.json().catch(() => ({})); | |
| 159 | err.textContent = r.ok || (r.status === 409 && body.you) ? "" : body.error ?? `could not join (${r.status})`; | |
| 160 | if (!err.textContent) { $("joinName").value = ""; lobby.ws?.close(); } | |
| 161 | } catch { err.textContent = "could not reach the app; try again"; } | |
| 162 | button.disabled = false; | |
| 163 | }; | |
| 164 | const chatBox = $("chat"); | |
| 165 | function chatLine(m) { | |
| 166 | const me = lobby.hello?.you; | |
| 167 | const line = el("div", { className: m.from ? `line${me && m.from.id === me.id ? " me" : ""}` : "line sys", title: new Date(m.at).toLocaleTimeString() }); | |
| 168 | line.dataset.id = m.id; | |
| 169 | if (m.from) { line.dataset.from = m.from.id; line.dataset.name = m.from.name; line.append(el("b", { textContent: m.from.name })); } | |
| 170 | line.append(el("span", { textContent: m.text })); | |
| 171 | if (m.from && me?.owner) line.tabIndex = 0; | |
| 172 | return line; | |
| 173 | } | |
| 174 | // A new page gets the last lines of the chat; older ones come a page at a time, when asked for. | |
| 175 | const earlier = el("button", { type: "button", className: "earlier", textContent: "Earlier messages" }); | |
| 176 | earlier.onclick = () => { | |
| 177 | const first = chatBox.querySelector(".line[data-id]"); | |
| 178 | if (!first) return; | |
| 179 | earlier.disabled = true; | |
| 180 | say({ type: "history", before: Number(first.dataset.id) }); | |
| 181 | }; | |
| 182 | function showEarlier(more) { earlier.disabled = false; if (more) chatBox.prepend(earlier); else earlier.remove(); } | |
| 183 | function addOlder(lines, more) { | |
| 184 | const below = chatBox.scrollHeight - chatBox.scrollTop; // the reader stays on the line they were reading | |
| 185 | chatBox.prepend(...lines.map(chatLine)); | |
| 186 | chatBox.scrollTop = chatBox.scrollHeight - below; | |
| 187 | showEarlier(more); | |
| 188 | } | |
| 189 | function addChat(lines, replace = false) { | |
| 190 | const atEnd = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight < 40; | |
| 191 | if (replace) chatBox.replaceChildren(); | |
| 192 | chatBox.append(...lines.map(chatLine)); | |
| 193 | if (!replace) while (chatBox.querySelectorAll(".line").length > 200) chatBox.querySelector(".line").remove(); | |
| 194 | if (atEnd || replace) chatBox.scrollTop = chatBox.scrollHeight; | |
| 195 | if (!replace && tab() !== "chat") $("unread").textContent = String(Math.min(99, Number($("unread").textContent || 0) + lines.length)); | |
| 196 | } | |
| 197 | // Moderation on a phone: long-press a line (or right-click it, or Enter on it) for delete and mute. | |
| 198 | { | |
| 199 | let press = null, held = null; | |
| 200 | const open = (line) => { | |
| 201 | if (!lobby.hello?.you?.owner || !line?.dataset.from) return; | |
| 202 | held = line; line.classList.add("held"); | |
| 203 | $("modTitle").textContent = `${line.dataset.name} said`; | |
| 204 | $("modText").textContent = line.querySelector("span")?.textContent ?? ""; | |
| 205 | $("modMute").textContent = `Mute ${line.dataset.name}`; | |
| 206 | $("modBan").textContent = `Ban ${line.dataset.name}`; | |
| 207 | $("modMute").hidden = $("modBan").hidden = line.dataset.from === lobby.hello.you.id; | |
| 208 | $("modDlg").showModal(); | |
| 209 | navigator.vibrate?.(10); | |
| 210 | }; | |
| 211 | chatBox.addEventListener("pointerdown", (e) => { | |
| 212 | const line = e.target.closest(".line"); if (!line?.dataset.from || !lobby.hello?.you?.owner) return; | |
| 213 | press = { x: e.clientX, y: e.clientY, timer: setTimeout(() => { press = null; open(line); }, 480) }; | |
| 214 | }); | |
| 215 | const cancel = () => { if (press) { clearTimeout(press.timer); press = null; } }; | |
| 216 | chatBox.addEventListener("pointermove", (e) => { if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) cancel(); }); | |
| 217 | for (const ev of ["pointerup", "pointercancel", "scroll"]) chatBox.addEventListener(ev, cancel); | |
| 218 | chatBox.addEventListener("contextmenu", (e) => { const line = e.target.closest(".line"); if (line?.dataset.from && lobby.hello?.you?.owner) { e.preventDefault(); cancel(); open(line); } }); | |
| 219 | chatBox.addEventListener("keydown", (e) => { if (e.key === "Enter" && e.target.classList?.contains("line")) open(e.target); }); | |
| 220 | $("modDlg").addEventListener("close", () => { | |
| 221 | const line = held; held = null; line?.classList.remove("held"); | |
| 222 | if (!line) return; | |
| 223 | if ($("modDlg").returnValue === "delete") say({ type: "delete", id: Number(line.dataset.id) }); | |
| 224 | if ($("modDlg").returnValue === "mute") say({ type: "mute", id: line.dataset.from, on: true }); | |
| 225 | if ($("modDlg").returnValue === "ban" && confirm(`Ban ${line.dataset.name}? They can still watch, but nobody from their name, browser or address can chat or drive.`)) say({ type: "ban", id: line.dataset.from, on: true }); | |
| 226 | }); | |
| 227 | } | |
| 228 | function lobbyConnect() { | |
| 229 | const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`); | |
| 230 | lobby.ws = ws; | |
| 231 | ws.onopen = () => { lobby.retry = 500; }; | |
| 232 | ws.onmessage = (e) => { | |
| 233 | const m = JSON.parse(e.data); | |
| 234 | if (m.type === "ping") return say({ type: "pong" }); | |
| 235 | if (m.type === "status") { lobby.statusSeen = true; return m.status ? applyStatus(m.status) : noStatus(); } | |
| 236 | if (m.type === "hello") lobby.hello = m; | |
| 237 | else if (m.type === "state") { lobby.offset = m.now - Date.now(); lobby.state = m; } | |
| 238 | else if (m.type === "chat") return addChat(m.messages, true), showEarlier(m.more); | |
| 239 | else if (m.type === "history") return addOlder(m.messages, m.more); | |
| 240 | else if (m.type === "said") return addChat([m.message]); | |
| 241 | else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove(); | |
| 242 | else if (m.type === "muted") lobby.mutedList = m.muted; | |
| 243 | else if (m.type === "banned") lobby.bannedList = m.banned; | |
| 244 | else if (m.type === "words") { const f = $("wordsForm"); if (document.activeElement !== f.elements.words) f.elements.words.value = m.words.join(", "); if (wordsSent) { wordsSent = false; msg(`Word filter saved: ${m.words.length} word${m.words.length === 1 ? "" : "s"}.`); } } | |
| 245 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; fillAdmin(saved); } | |
| 246 | else if (m.type === "crew") lobby.crew = m; | |
| 247 | else if (m.type === "error") return msg(m.error, true); | |
| 248 | renderTurn(); | |
| 249 | }; | |
| 250 | ws.onclose = () => { | |
| 251 | if (lobby.ws !== ws) return; | |
| 252 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back | |
| 253 | applyLock(); | |
| 254 | $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…"; | |
| 255 | setTimeout(lobbyConnect, lobby.retry); | |
| 256 | lobby.retry = Math.min(lobby.retry * 2, 8000); | |
| 257 | }; | |
| 258 | } | |
| 259 | // The owner's settings: filled from the server whenever they change, unless the owner is typing in the form. | |
| 260 | function fillAdmin(saved) { | |
| 261 | const form = $("adminForm"); | |
| 262 | if (!lobby.admin || form.contains(document.activeElement)) return; | |
| 263 | for (const [k, v] of Object.entries(lobby.admin.settings)) if (form.elements[k]) form.elements[k].value = v; | |
| 264 | if (saved && form.dataset.sent) { delete form.dataset.sent; msg("settings saved"); } | |
| 265 | } | |
| 266 | $("adminForm").onsubmit = (e) => { | |
| 267 | e.preventDefault(); | |
| 268 | const f = $("adminForm").elements; | |
| 269 | const set = { announcement: f.announcement.value }; | |
| 270 | for (const k of ["turnSeconds", "idleSeconds", "maxSpeedPercent", "maxQueue"]) set[k] = Number(f[k].value); | |
| 271 | $("adminForm").dataset.sent = "1"; | |
| 272 | document.activeElement?.blur(); | |
| 273 | say({ type: "settings", set }); | |
| 274 | }; | |
| 275 | $("say").onsubmit = (e) => { | |
| 276 | e.preventDefault(); | |
| 277 | const text = $("sayText").value.trim(); | |
| 278 | if (!text) return; | |
| 279 | say({ type: "post", text }); | |
| 280 | $("sayText").value = ""; | |
| 281 | chatBox.scrollTop = chatBox.scrollHeight; | |
| 282 | }; | |
| 283 | ||
| 284 | return { lobby, mayDrive, isOwner, say, chatBox, connect: lobbyConnect }; | |
| 285 | } |
Software/so101/src/ui/lobby-panel.test.ts added +24
| @@ -0,0 +1,24 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { minutes, ordinal, queueRow, waitMinutes } from "./lobby-panel.js"; | |
| 3 | ||
| 4 | describe("the room's pure helpers", () => { | |
| 5 | test("a queue entry carries the name as plain text for textContent, never as markup", () => { | |
| 6 | const name = `<img src=x onerror="alert(1)">`; | |
| 7 | const row = queueRow({ id: "a", name, place: 2, waitMs: 90_000 }, { id: "b" }); | |
| 8 | expect(row).toEqual({ className: "", place: "2.", name, wait: "≤ 2 min" }); | |
| 9 | expect(queueRow({ id: "b", name: "me", place: 1, waitMs: 0 }, { id: "b" })).toEqual({ className: "me", place: "1.", name: "me (you)", wait: "≤ 1 min" }); | |
| 10 | expect(queueRow({ id: "a", name: "x", place: 1, waitMs: 0 }, null).className).toBe(""); | |
| 11 | }); | |
| 12 | ||
| 13 | test("waits round up to a whole minute, at least one", () => { | |
| 14 | expect([0, 1, 60_000, 60_001].map(waitMinutes)).toEqual([1, 1, 1, 2]); | |
| 15 | }); | |
| 16 | ||
| 17 | test("the clock reads m:ss and never goes negative", () => { | |
| 18 | expect([0, 1, 61_000, -5].map(minutes)).toEqual(["0:00", "0:01", "1:01", "0:00"]); | |
| 19 | }); | |
| 20 | ||
| 21 | test("places read as ordinals, teens included", () => { | |
| 22 | expect([1, 2, 3, 4, 11, 12, 13, 21, 112].map(ordinal)).toEqual(["1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "21st", "112th"]); | |
| 23 | }); | |
| 24 | }); |
Software/so101/src/viewer.html +4 −260
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | <link rel="modulepreload" href="/ui/__VERSION__/camera-plan.js"> |
| 21 | 21 | <link rel="modulepreload" href="/ui/__VERSION__/drive.js"> |
| 22 | 22 | <link rel="modulepreload" href="/ui/__VERSION__/frames.js"> |
| 23 | <link rel="modulepreload" href="/ui/__VERSION__/lobby-panel.js"> | |
| 23 | 24 | <style> |
| 24 | 25 | /* Phone portrait first: the view on top, a status strip with the E-stop under it, a sheet of tabs below that. |
| 25 | 26 | Landscape on a phone: the view fills the screen and the strip and the sheet float over it. |
| @@ -517,6 +518,7 @@ | ||
| 517 | 518 | import { cameraPlan, QUALITIES, samePlan } from "/ui/__VERSION__/camera-plan.js"; |
| 518 | 519 | import { bindSurface, canDrive, Driver, shape, UP } from "/ui/__VERSION__/drive.js"; |
| 519 | 520 | import { Frames } from "/ui/__VERSION__/frames.js"; |
| 521 | import { createLobbyPanel } from "/ui/__VERSION__/lobby-panel.js"; | |
| 520 | 522 | |
| 521 | 523 | const $ = (id) => document.getElementById(id); |
| 522 | 524 | const q = new URLSearchParams(location.search); |
| @@ -1549,14 +1551,8 @@ | ||
| 1549 | 1551 | setInterval(() => { if (!$("metricsPanel").hidden) showMetrics(); }, 5000); |
| 1550 | 1552 | |
| 1551 | 1553 | // ---------------------------------------------------------------- the room: the turn, the queue and the chat over /live |
| 1552 | // Behind the hosted app's relay only the person whose turn it is may drive, and the server refuses everyone else. | |
| 1553 | // The page follows suit: the Controls tab appears on your turn. Everything here arrives on one socket. | |
| 1554 | let wordsSent = false; | |
| 1555 | $("wordsForm").addEventListener("submit", (e) => { e.preventDefault(); wordsSent = true; say({ type: "words", words: $("wordsForm").elements.words.value.split(",").map((w) => w.trim()).filter(Boolean) }); }); | |
| 1556 | const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false }; | |
| 1557 | function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); } | |
| 1558 | function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); } | |
| 1559 | const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); }; | |
| 1554 | // src/ui/lobby-panel.js holds the socket, the queue, the join form and the chat; the driving lock below follows what it hears. | |
| 1555 | const { lobby, mayDrive, isOwner, say, chatBox, connect: lobbyConnect } = createLobbyPanel({ $, el, msg, relayed, showTab, tab: () => tab, applyStatus: (s) => applyStatus(s), noStatus: () => noStatus(), applyLock: () => applyLock() }); | |
| 1560 | 1556 | let drove = false; |
| 1561 | 1557 | function explainLock() { |
| 1562 | 1558 | const me = lobby.hello?.you, down = linkNow === "offline", st = typeof status?.source === "string" && status.source.startsWith("simulated"); |
| @@ -1590,258 +1586,6 @@ | ||
| 1590 | 1586 | } |
| 1591 | 1587 | else if ($(`t-${tab}`).hidden) showTab(tab); |
| 1592 | 1588 | } |
| 1593 | const serverNow = () => Date.now() + lobby.offset; | |
| 1594 | const minutes = (ms) => { const t = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; }; | |
| 1595 | const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`; | |
| 1596 | function tickClock() { | |
| 1597 | const d = lobby.state?.driver, c = $("clock"), me = lobby.hello?.you; | |
| 1598 | if (!relayed) return void (c.textContent = "On this machine: no sign-in, every visitor drives."); | |
| 1599 | if (!lobby.state || !lobby.hello?.signin) return void (c.textContent = lobby.hello && !lobby.hello.signin ? "Local: no sign-in, every visitor drives." : ""); | |
| 1600 | const mine = me ? lobby.state.queue.find((x) => x.id === me.id) : null; | |
| 1601 | const place = mine ? ` · you're ${ordinal(mine.place)} in line, ≤ ${Math.max(1, Math.ceil(mine.waitMs / 60000))} min` : ""; | |
| 1602 | if (!d) $("ring").hidden = true; | |
| 1603 | if (!d) { c.className = ""; c.textContent = lobby.state.paused ? `No new turns until the owner resumes${place || "; you can still join the line"}.` : "Free: take control to drive."; return; } | |
| 1604 | const now = serverNow(), idle = d.idleEndsAt - now; | |
| 1605 | const idleSoon = idle < 15000 && d.idleEndsAt < d.endsAt; | |
| 1606 | c.className = idleSoon || d.readyBy ? "idle" : ""; | |
| 1607 | tickRing(d, me, now); | |
| 1608 | if (d.readyBy && me && d.id === me.id) return void (c.textContent = `Tap Ready within ${Math.max(0, Math.ceil((d.readyBy - now) / 1000))} s or the turn passes on`); | |
| 1609 | c.textContent = idleSoon ? `Idle: the turn ends in ${Math.max(0, Math.ceil(idle / 1000))} s unless the arm moves` : `${minutes(d.endsAt - now)} left${place}`; | |
| 1610 | } | |
| 1611 | /** The ring is the driver's own: time left on the turn, in the seconds around it. */ | |
| 1612 | function tickRing(d, me, now) { | |
| 1613 | const ring = $("ring"), mine = Boolean(me && d.id === me.id), st = lobby.state; | |
| 1614 | ring.hidden = !mine; | |
| 1615 | if (!mine) return; | |
| 1616 | const left = Math.max(0, d.endsAt - now); | |
| 1617 | ring.style.setProperty("--p", `${Math.min(100, (left / Math.max(st.turnMs, 1)) * 100)}%`); | |
| 1618 | ring.classList.toggle("low", left < 15000); | |
| 1619 | $("ringN").textContent = left >= 60000 ? `${Math.ceil(left / 60000)}m` : `${Math.ceil(left / 1000)}`; | |
| 1620 | } | |
| 1621 | setInterval(tickClock, 250); | |
| 1622 | $("quiet").onchange = (e) => { try { localStorage.setItem("so101.quiet", e.target.checked ? "1" : "0"); } catch {} }; | |
| 1623 | /** "You're next": a tone and a buzz (Android) and an amber strip; no web push, so only while the page is open. */ | |
| 1624 | let wasNext = false; | |
| 1625 | const quiet = () => { try { return localStorage.getItem("so101.quiet") === "1"; } catch { return false; } }; | |
| 1626 | function alertNext(next) { | |
| 1627 | $("strip").classList.toggle("next", next); | |
| 1628 | if (next && !wasNext) { | |
| 1629 | navigator.vibrate?.([200, 100, 200]); | |
| 1630 | if (!quiet()) try { | |
| 1631 | const ctx = new (window.AudioContext || window.webkitAudioContext)(), o = ctx.createOscillator(), g = ctx.createGain(); | |
| 1632 | o.frequency.value = 880; g.gain.value = 0.08; o.connect(g); g.connect(ctx.destination); o.start(); o.stop(ctx.currentTime + 0.25); o.onended = () => ctx.close(); | |
| 1633 | } catch { /* autoplay refused: the amber strip is the alert */ } | |
| 1634 | } | |
| 1635 | wasNext = next; | |
| 1636 | } | |
| 1637 | const button = (textContent, className, onclick) => el("button", { textContent, className, type: "button", onclick }); | |
| 1638 | /** The one thing to do about the turn, short enough for the strip. */ | |
| 1639 | function turnButtons() { | |
| 1640 | const st = lobby.state, me = lobby.hello?.you ?? null, d = st?.driver; | |
| 1641 | if (!st || !lobby.hello?.signin) return []; // a run on one's own machine: everyone drives, nobody queues | |
| 1642 | if (!me) return [button("Join to drive", "go", () => { showTab("queue"); $("joinName").focus(); })]; | |
| 1643 | if (lobby.hello.banned) return []; // banned: watching only | |
| 1644 | if (d?.id === me.id) return [...(d.readyBy ? [button("Ready", "go ready", () => say({ type: "ready" }))] : []), ...(!st.queue.length && !d.readyBy ? [button("+30 s", "", () => say({ type: "extend" }))] : []), button("Hand back", "", () => say({ type: "leave" }))]; | |
| 1645 | if (st.queue.some((x) => x.id === me.id)) return [button("Leave", "", () => say({ type: "leave" }))]; | |
| 1646 | return [button(me.owner && d ? "Take over" : d || (st.paused && !me.owner) ? "Join queue" : "Take control", "go", () => say({ type: "join" }))]; | |
| 1647 | } | |
| 1648 | function renderTurn() { | |
| 1649 | const st = lobby.state, me = lobby.hello?.you ?? null; | |
| 1650 | if (!st || !lobby.hello) return; | |
| 1651 | const d = st.driver; | |
| 1652 | $("driverLine").className = st.paused ? "paused" : d ? "" : "none"; | |
| 1653 | const mine = me ? st.queue.find((x) => x.id === me.id) : null, driving = Boolean(me && d?.id === me.id); | |
| 1654 | // The strip in words: watching, queued, next, your turn. | |
| 1655 | const wait = Math.max(1, Math.ceil((st.queue.length ? st.queue.at(-1).waitMs + st.turnMs : d ? Math.max(0, d.endsAt - st.now) : 0) / 60000)); | |
| 1656 | $("driverLine").textContent = (st.paused ? "Paused for maintenance" + (d ? " · " : "") : "") + | |
| 1657 | (driving ? (d.readyBy ? "Your turn · confirm you're here" : "Your turn") : mine ? (mine.place === 1 ? "You're next" : `#${mine.place} · ~${Math.max(1, Math.ceil(mine.waitMs / 60000))} min`) : | |
| 1658 | d ? (lobby.hello.signin && !lobby.hello.banned ? `Join queue · ${st.queue.length} waiting · ~${wait} min` : `${d.name} has control`) : st.paused ? "" : "Nobody has control"); | |
| 1659 | $("driverTag").textContent = d ? `🎮 ${d.name}${driving ? " (you)" : ""}` : ""; | |
| 1660 | $("strip").classList.toggle("ready", Boolean(driving && d.readyBy)); | |
| 1661 | alertNext(Boolean(mine && mine.place === 1 && !st.paused)); | |
| 1662 | $("notice").hidden = !st.announcement; | |
| 1663 | $("notice").textContent = st.announcement ?? ""; | |
| 1664 | $("capLine").textContent = st.maxSpeedPercent < 100 ? `Speed limited to ${st.maxSpeedPercent}% of full` : ""; | |
| 1665 | $("turnActions").replaceChildren(...turnButtons()); | |
| 1666 | $("quiet").checked = quiet(); | |
| 1667 | $("queueActions").replaceChildren(el("span", { textContent: d ? (me && d.id === me.id ? "You" : d.name) : "Nobody", style: "flex:1;font-weight:600" }), ...turnButtons()); | |
| 1668 | const joining = lobby.hello.signin && !me; | |
| 1669 | $("joinForm").hidden = $("forgeSignin").hidden = !joining; | |
| 1670 | if (!joining) $("joinErr").textContent = ""; | |
| 1671 | $("forgeSignin").href = `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`; | |
| 1672 | $("waiting").textContent = st.queue.length ? String(st.queue.length) : ""; | |
| 1673 | $("queue").replaceChildren(...st.queue.map((x) => { | |
| 1674 | const mine = me && x.id === me.id; | |
| 1675 | const li = el("li", { className: mine ? "me" : "" }, el("span", { className: "place", textContent: `${x.place}.` }), el("span", { textContent: mine ? `${x.name} (you)` : x.name }), el("span", { className: "wait", textContent: `≤ ${Math.max(1, Math.ceil(x.waitMs / 60000))} min` })); | |
| 1676 | if (me?.owner) { const b = button("×", "x", () => say({ type: "end", id: x.id })); b.setAttribute("aria-label", `take ${x.name} out of the line`); li.append(b); } | |
| 1677 | return li; | |
| 1678 | })); | |
| 1679 | $("modTurn").replaceChildren(...(me?.owner && d && d.id !== me.id ? [button(`End ${d.name}'s turn`, "danger", () => say({ type: "end", id: d.id }))] : [el("span", { className: "note", textContent: d ? "You are driving." : "Nobody is driving.", style: "color:var(--dim)" })])); | |
| 1680 | if (me?.owner) { | |
| 1681 | $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue"; | |
| 1682 | $("pauseBtn").className = st.paused ? "go" : ""; | |
| 1683 | $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused }); | |
| 1684 | } | |
| 1685 | $("mutedLine").replaceChildren(...(me?.owner ? lobby.mutedList.map((m) => el("div", { className: "item" }, el("span", { textContent: `${m.name} is muted` }), button("Unmute", "", () => say({ type: "mute", id: m.id, on: false })))) : [])); | |
| 1686 | $("bannedLine").replaceChildren(...(me?.owner ? lobby.bannedList.map((b) => el("div", { className: "item" }, el("span", { textContent: `${b.name} is banned` }), button("Unban", "", () => say({ type: "ban", id: b.id, on: false })))) : [])); | |
| 1687 | renderCrew(me); | |
| 1688 | $("say").hidden = !me || lobby.hello.muted || lobby.hello.banned; | |
| 1689 | $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Join (Queue tab) to chat." : lobby.hello.banned ? "You are banned: you can still watch." : lobby.hello.muted ? "The owner has muted you." : ""; | |
| 1690 | chatBox.classList.toggle("moderated", Boolean(me?.owner)); | |
| 1691 | tickClock(); | |
| 1692 | applyLock(); | |
| 1693 | } | |
| 1694 | /** The owner's view of the crew moderator: on/off, the rules, lines it hid, people it suggests muting. */ | |
| 1695 | function renderCrew(me) { | |
| 1696 | const c = lobby.crew; | |
| 1697 | const box = $("crewLine"); | |
| 1698 | if (!me?.owner || !c?.settings) return box.replaceChildren(el("p", { textContent: me?.owner ? "Waiting for the moderator's settings." : "" })); | |
| 1699 | if (box.contains(document.activeElement) && document.activeElement.matches("textarea, input")) return; // do not drop what is being typed | |
| 1700 | const perMinute = el("input", { type: "number", min: 1, max: 600, step: 1, value: c.settings.maxPerMinute, id: "crewMax", inputMode: "numeric" }); | |
| 1701 | const rules = el("textarea", { value: c.settings.rules, rows: 3, maxLength: 2000, ariaLabel: "Room rules for the crew moderator" }); | |
| 1702 | const item = (text, ...buttons) => el("div", { className: "item" }, el("span", { textContent: text }), ...buttons); | |
| 1703 | box.replaceChildren( | |
| 1704 | item(c.available ? (c.settings.enabled ? "On: every chat line is checked." : "Off.") : "No model reachable: nothing is checked.", | |
| 1705 | button(c.settings.enabled ? "Turn off" : "Turn on", "", () => say({ type: "crew", settings: { enabled: !c.settings.enabled } }))), | |
| 1706 | el("div", { className: "item" }, el("label", { htmlFor: "crewMax", textContent: "Most lines checked per minute" }), perMinute, | |
| 1707 | button("Save", "", () => say({ type: "crew", settings: { maxPerMinute: Number(perMinute.value) } }))), | |
| 1708 | rules, el("div", { className: "row" }, button("Save rules", "", () => say({ type: "crew", settings: { rules: rules.value } }))), | |
| 1709 | ...c.hidden.map((h) => item(`Hidden: ${h.message.from?.name}: ${h.message.text} (${h.reason})`, button("Restore", "", () => say({ type: "restore", id: h.message.id })))), | |
| 1710 | ...c.suggestions.map((x) => item(`Suggests muting ${x.message.from?.name}: ${x.message.text} (${x.reason})`, button("Mute", "danger", () => say({ type: "mute", id: x.message.from.id, on: true })), button("Dismiss", "", () => say({ type: "dismiss", id: x.message.id }))))); | |
| 1711 | } | |
| 1712 | /** Join: one field, one button. The answer sets the session cookie; the room is reopened to hear who you are now. */ | |
| 1713 | $("joinForm").onsubmit = async (e) => { | |
| 1714 | e.preventDefault(); | |
| 1715 | const button = $("joinForm").querySelector("button"), err = $("joinErr"); | |
| 1716 | button.disabled = true; | |
| 1717 | try { | |
| 1718 | const r = await fetch("/join", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: $("joinName").value.trim() }) }); | |
| 1719 | const body = await r.json().catch(() => ({})); | |
| 1720 | err.textContent = r.ok || (r.status === 409 && body.you) ? "" : body.error ?? `could not join (${r.status})`; | |
| 1721 | if (!err.textContent) { $("joinName").value = ""; lobby.ws?.close(); } | |
| 1722 | } catch { err.textContent = "could not reach the app; try again"; } | |
| 1723 | button.disabled = false; | |
| 1724 | }; | |
| 1725 | const chatBox = $("chat"); | |
| 1726 | function chatLine(m) { | |
| 1727 | const me = lobby.hello?.you; | |
| 1728 | const line = el("div", { className: m.from ? `line${me && m.from.id === me.id ? " me" : ""}` : "line sys", title: new Date(m.at).toLocaleTimeString() }); | |
| 1729 | line.dataset.id = m.id; | |
| 1730 | if (m.from) { line.dataset.from = m.from.id; line.dataset.name = m.from.name; line.append(el("b", { textContent: m.from.name })); } | |
| 1731 | line.append(el("span", { textContent: m.text })); | |
| 1732 | if (m.from && me?.owner) line.tabIndex = 0; | |
| 1733 | return line; | |
| 1734 | } | |
| 1735 | // A new page gets the last lines of the chat; older ones come a page at a time, when asked for. | |
| 1736 | const earlier = el("button", { type: "button", className: "earlier", textContent: "Earlier messages" }); | |
| 1737 | earlier.onclick = () => { | |
| 1738 | const first = chatBox.querySelector(".line[data-id]"); | |
| 1739 | if (!first) return; | |
| 1740 | earlier.disabled = true; | |
| 1741 | say({ type: "history", before: Number(first.dataset.id) }); | |
| 1742 | }; | |
| 1743 | function showEarlier(more) { earlier.disabled = false; if (more) chatBox.prepend(earlier); else earlier.remove(); } | |
| 1744 | function addOlder(lines, more) { | |
| 1745 | const below = chatBox.scrollHeight - chatBox.scrollTop; // the reader stays on the line they were reading | |
| 1746 | chatBox.prepend(...lines.map(chatLine)); | |
| 1747 | chatBox.scrollTop = chatBox.scrollHeight - below; | |
| 1748 | showEarlier(more); | |
| 1749 | } | |
| 1750 | function addChat(lines, replace = false) { | |
| 1751 | const atEnd = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight < 40; | |
| 1752 | if (replace) chatBox.replaceChildren(); | |
| 1753 | chatBox.append(...lines.map(chatLine)); | |
| 1754 | if (!replace) while (chatBox.querySelectorAll(".line").length > 200) chatBox.querySelector(".line").remove(); | |
| 1755 | if (atEnd || replace) chatBox.scrollTop = chatBox.scrollHeight; | |
| 1756 | if (!replace && tab !== "chat") $("unread").textContent = String(Math.min(99, Number($("unread").textContent || 0) + lines.length)); | |
| 1757 | } | |
| 1758 | // Moderation on a phone: long-press a line (or right-click it, or Enter on it) for delete and mute. | |
| 1759 | { | |
| 1760 | let press = null, held = null; | |
| 1761 | const open = (line) => { | |
| 1762 | if (!lobby.hello?.you?.owner || !line?.dataset.from) return; | |
| 1763 | held = line; line.classList.add("held"); | |
| 1764 | $("modTitle").textContent = `${line.dataset.name} said`; | |
| 1765 | $("modText").textContent = line.querySelector("span")?.textContent ?? ""; | |
| 1766 | $("modMute").textContent = `Mute ${line.dataset.name}`; | |
| 1767 | $("modBan").textContent = `Ban ${line.dataset.name}`; | |
| 1768 | $("modMute").hidden = $("modBan").hidden = line.dataset.from === lobby.hello.you.id; | |
| 1769 | $("modDlg").showModal(); | |
| 1770 | navigator.vibrate?.(10); | |
| 1771 | }; | |
| 1772 | chatBox.addEventListener("pointerdown", (e) => { | |
| 1773 | const line = e.target.closest(".line"); if (!line?.dataset.from || !lobby.hello?.you?.owner) return; | |
| 1774 | press = { x: e.clientX, y: e.clientY, timer: setTimeout(() => { press = null; open(line); }, 480) }; | |
| 1775 | }); | |
| 1776 | const cancel = () => { if (press) { clearTimeout(press.timer); press = null; } }; | |
| 1777 | chatBox.addEventListener("pointermove", (e) => { if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) cancel(); }); | |
| 1778 | for (const ev of ["pointerup", "pointercancel", "scroll"]) chatBox.addEventListener(ev, cancel); | |
| 1779 | chatBox.addEventListener("contextmenu", (e) => { const line = e.target.closest(".line"); if (line?.dataset.from && lobby.hello?.you?.owner) { e.preventDefault(); cancel(); open(line); } }); | |
| 1780 | chatBox.addEventListener("keydown", (e) => { if (e.key === "Enter" && e.target.classList?.contains("line")) open(e.target); }); | |
| 1781 | $("modDlg").addEventListener("close", () => { | |
| 1782 | const line = held; held = null; line?.classList.remove("held"); | |
| 1783 | if (!line) return; | |
| 1784 | if ($("modDlg").returnValue === "delete") say({ type: "delete", id: Number(line.dataset.id) }); | |
| 1785 | if ($("modDlg").returnValue === "mute") say({ type: "mute", id: line.dataset.from, on: true }); | |
| 1786 | if ($("modDlg").returnValue === "ban" && confirm(`Ban ${line.dataset.name}? They can still watch, but nobody from their name, browser or address can chat or drive.`)) say({ type: "ban", id: line.dataset.from, on: true }); | |
| 1787 | }); | |
| 1788 | } | |
| 1789 | function lobbyConnect() { | |
| 1790 | const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`); | |
| 1791 | lobby.ws = ws; | |
| 1792 | ws.onopen = () => { lobby.retry = 500; }; | |
| 1793 | ws.onmessage = (e) => { | |
| 1794 | const m = JSON.parse(e.data); | |
| 1795 | if (m.type === "ping") return say({ type: "pong" }); | |
| 1796 | if (m.type === "status") { lobby.statusSeen = true; return m.status ? applyStatus(m.status) : noStatus(); } | |
| 1797 | if (m.type === "hello") lobby.hello = m; | |
| 1798 | else if (m.type === "state") { lobby.offset = m.now - Date.now(); lobby.state = m; } | |
| 1799 | else if (m.type === "chat") return addChat(m.messages, true), showEarlier(m.more); | |
| 1800 | else if (m.type === "history") return addOlder(m.messages, m.more); | |
| 1801 | else if (m.type === "said") return addChat([m.message]); | |
| 1802 | else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove(); | |
| 1803 | else if (m.type === "muted") lobby.mutedList = m.muted; | |
| 1804 | else if (m.type === "banned") lobby.bannedList = m.banned; | |
| 1805 | else if (m.type === "words") { const f = $("wordsForm"); if (document.activeElement !== f.elements.words) f.elements.words.value = m.words.join(", "); if (wordsSent) { wordsSent = false; msg(`Word filter saved: ${m.words.length} word${m.words.length === 1 ? "" : "s"}.`); } } | |
| 1806 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; fillAdmin(saved); } | |
| 1807 | else if (m.type === "crew") lobby.crew = m; | |
| 1808 | else if (m.type === "error") return msg(m.error, true); | |
| 1809 | renderTurn(); | |
| 1810 | }; | |
| 1811 | ws.onclose = () => { | |
| 1812 | if (lobby.ws !== ws) return; | |
| 1813 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back | |
| 1814 | applyLock(); | |
| 1815 | $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…"; | |
| 1816 | setTimeout(lobbyConnect, lobby.retry); | |
| 1817 | lobby.retry = Math.min(lobby.retry * 2, 8000); | |
| 1818 | }; | |
| 1819 | } | |
| 1820 | // The owner's settings: filled from the server whenever they change, unless the owner is typing in the form. | |
| 1821 | function fillAdmin(saved) { | |
| 1822 | const form = $("adminForm"); | |
| 1823 | if (!lobby.admin || form.contains(document.activeElement)) return; | |
| 1824 | for (const [k, v] of Object.entries(lobby.admin.settings)) if (form.elements[k]) form.elements[k].value = v; | |
| 1825 | if (saved && form.dataset.sent) { delete form.dataset.sent; msg("settings saved"); } | |
| 1826 | } | |
| 1827 | $("adminForm").onsubmit = (e) => { | |
| 1828 | e.preventDefault(); | |
| 1829 | const f = $("adminForm").elements; | |
| 1830 | const set = { announcement: f.announcement.value }; | |
| 1831 | for (const k of ["turnSeconds", "idleSeconds", "maxSpeedPercent", "maxQueue"]) set[k] = Number(f[k].value); | |
| 1832 | $("adminForm").dataset.sent = "1"; | |
| 1833 | document.activeElement?.blur(); | |
| 1834 | say({ type: "settings", set }); | |
| 1835 | }; | |
| 1836 | $("say").onsubmit = (e) => { | |
| 1837 | e.preventDefault(); | |
| 1838 | const text = $("sayText").value.trim(); | |
| 1839 | if (!text) return; | |
| 1840 | say({ type: "post", text }); | |
| 1841 | $("sayText").value = ""; | |
| 1842 | chatBox.scrollTop = chatBox.scrollHeight; | |
| 1843 | }; | |
| 1844 | ||
| 1845 | 1589 | // ---------------------------------------------------------------- 3D calibration |
| 1846 | 1590 | // The panel and its words are fetched the first time someone opens it: src/ui/calibration.js. |
| 1847 | 1591 | $("calib").onclick = async () => { |
new above
offline