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 (from main at 1142ee6, forge.json untouched) #170
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
smith/arm:smith/158-the-page-s-queue-join-and-chat-script-li → main 2 commits fork 1 thread · 1 unresolved
4 files
changed +345
−242
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 51.2 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(51_200); | |
| 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 +270
| @@ -0,0 +1,270 @@ | ||
| 1 | // @ts-check | |
| 2 | /** | |
| 3 | * The room on the page: the turn, the queue and the chat over /live. Moved out of viewer.html; the page hands in what | |
| 4 | * it owns (the DOM helpers, the tabs, the lock and the arm's status) and gets back the room's state and its few calls. | |
| 5 | * Everything a person typed goes in with textContent. The pure helpers are tested in ./lobby-panel.test.ts. | |
| 6 | */ | |
| 7 | ||
| 8 | /** @param {number} ms @returns {string} m:ss, never negative */ | |
| 9 | export const minutes = (ms) => { const t = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; }; | |
| 10 | /** @param {number} n @returns {string} 1st, 2nd, 11th */ | |
| 11 | export const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`; | |
| 12 | /** @param {number} ms @returns {number} whole minutes to wait, at least one */ | |
| 13 | export const waitMinutes = (ms) => Math.max(1, Math.ceil(ms / 60000)); | |
| 14 | ||
| 15 | /** | |
| 16 | * One line of the queue. The name goes in as text, so a name can never be markup. | |
| 17 | * @param {(tag: string, props?: Record<string, unknown>, ...children: any[]) => any} el | |
| 18 | * @param {{ id: string, name: string, place: number, waitMs: number }} x | |
| 19 | * @param {boolean} mine | |
| 20 | */ | |
| 21 | export function queueEntry(el, x, mine) { | |
| 22 | return 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: `≤ ${waitMinutes(x.waitMs)} min` })); | |
| 23 | } | |
| 24 | ||
| 25 | /** | |
| 26 | * @param {any} page what the page owns: $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin | |
| 27 | */ | |
| 28 | export function createRoom(page) { | |
| 29 | const { $, el, relayed, msg } = page; | |
| 30 | const doc = /** @type {any} */ (globalThis).document, nav = /** @type {any} */ (globalThis).navigator; | |
| 31 | const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false }; | |
| 32 | function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); } | |
| 33 | function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); } | |
| 34 | const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); }; | |
| 35 | const serverNow = () => Date.now() + lobby.offset; | |
| 36 | function tickClock() { | |
| 37 | const d = lobby.state?.driver, c = $("clock"), me = lobby.hello?.you; | |
| 38 | if (!relayed) return void (c.textContent = "On this machine: no sign-in, every visitor drives."); | |
| 39 | if (!lobby.state || !lobby.hello?.signin) return void (c.textContent = lobby.hello && !lobby.hello.signin ? "Local: no sign-in, every visitor drives." : ""); | |
| 40 | const mine = me ? lobby.state.queue.find((x) => x.id === me.id) : null; | |
| 41 | const place = mine ? ` · you're ${ordinal(mine.place)} in line, ≤ ${Math.max(1, Math.ceil(mine.waitMs / 60000))} min` : ""; | |
| 42 | if (!d) $("ring").hidden = true; | |
| 43 | 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; } | |
| 44 | const now = serverNow(), idle = d.idleEndsAt - now; | |
| 45 | const idleSoon = idle < 15000 && d.idleEndsAt < d.endsAt; | |
| 46 | c.className = idleSoon || d.readyBy ? "idle" : ""; | |
| 47 | tickRing(d, me, now); | |
| 48 | 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`); | |
| 49 | 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}`; | |
| 50 | } | |
| 51 | /** The ring is the driver's own: time left on the turn, in the seconds around it. */ | |
| 52 | function tickRing(d, me, now) { | |
| 53 | const ring = $("ring"), mine = Boolean(me && d.id === me.id), st = lobby.state; | |
| 54 | ring.hidden = !mine; | |
| 55 | if (!mine) return; | |
| 56 | const left = Math.max(0, d.endsAt - now); | |
| 57 | ring.style.setProperty("--p", `${Math.min(100, (left / Math.max(st.turnMs, 1)) * 100)}%`); | |
| 58 | ring.classList.toggle("low", left < 15000); | |
| 59 | $("ringN").textContent = left >= 60000 ? `${Math.ceil(left / 60000)}m` : `${Math.ceil(left / 1000)}`; | |
| 60 | } | |
| 61 | setInterval(tickClock, 250); | |
| 62 | $("quiet").onchange = (e) => { try { localStorage.setItem("so101.quiet", e.target.checked ? "1" : "0"); } catch {} }; | |
| 63 | /** "You're next": a tone and a buzz (Android) and an amber strip; no web push, so only while the page is open. */ | |
| 64 | let wasNext = false; | |
| 65 | const quiet = () => { try { return localStorage.getItem("so101.quiet") === "1"; } catch { return false; } }; | |
| 66 | function alertNext(next) { | |
| 67 | $("strip").classList.toggle("next", next); | |
| 68 | if (next && !wasNext) { | |
| 69 | nav.vibrate?.([200, 100, 200]); | |
| 70 | if (!quiet()) try { | |
| 71 | const ctx = new (window.AudioContext || window.webkitAudioContext)(), o = ctx.createOscillator(), g = ctx.createGain(); | |
| 72 | 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(); | |
| 73 | } catch { /* autoplay refused: the amber strip is the alert */ } | |
| 74 | } | |
| 75 | wasNext = next; | |
| 76 | } | |
| 77 | const button = (textContent, className, onclick) => el("button", { textContent, className, type: "button", onclick }); | |
| 78 | /** The one thing to do about the turn, short enough for the strip. */ | |
| 79 | function turnButtons() { | |
| 80 | const st = lobby.state, me = lobby.hello?.you ?? null, d = st?.driver; | |
| 81 | if (!st || !lobby.hello?.signin) return []; // a run on one's own machine: everyone drives, nobody queues | |
| 82 | if (!me) return [button("Join to drive", "go", () => { page.showTab("queue"); $("joinName").focus(); })]; | |
| 83 | if (lobby.hello.banned) return []; // banned: watching only | |
| 84 | 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" }))]; | |
| 85 | if (st.queue.some((x) => x.id === me.id)) return [button("Leave", "", () => say({ type: "leave" }))]; | |
| 86 | return [button(me.owner && d ? "Take over" : d || (st.paused && !me.owner) ? "Join queue" : "Take control", "go", () => say({ type: "join" }))]; | |
| 87 | } | |
| 88 | function renderTurn() { | |
| 89 | const st = lobby.state, me = lobby.hello?.you ?? null; | |
| 90 | if (!st || !lobby.hello) return; | |
| 91 | const d = st.driver; | |
| 92 | $("driverLine").className = st.paused ? "paused" : d ? "" : "none"; | |
| 93 | const mine = me ? st.queue.find((x) => x.id === me.id) : null, driving = Boolean(me && d?.id === me.id); | |
| 94 | // The strip in words: watching, queued, next, your turn. | |
| 95 | 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)); | |
| 96 | $("driverLine").textContent = (st.paused ? "Paused for maintenance" + (d ? " · " : "") : "") + | |
| 97 | (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`) : | |
| 98 | d ? (lobby.hello.signin && !lobby.hello.banned ? `Join queue · ${st.queue.length} waiting · ~${wait} min` : `${d.name} has control`) : st.paused ? "" : "Nobody has control"); | |
| 99 | $("driverTag").textContent = d ? `🎮 ${d.name}${driving ? " (you)" : ""}` : ""; | |
| 100 | $("strip").classList.toggle("ready", Boolean(driving && d.readyBy)); | |
| 101 | alertNext(Boolean(mine && mine.place === 1 && !st.paused)); | |
| 102 | $("notice").hidden = !st.announcement; | |
| 103 | $("notice").textContent = st.announcement ?? ""; | |
| 104 | $("capLine").textContent = st.maxSpeedPercent < 100 ? `Speed limited to ${st.maxSpeedPercent}% of full` : ""; | |
| 105 | $("turnActions").replaceChildren(...turnButtons()); | |
| 106 | $("quiet").checked = quiet(); | |
| 107 | $("queueActions").replaceChildren(el("span", { textContent: d ? (me && d.id === me.id ? "You" : d.name) : "Nobody", style: "flex:1;font-weight:600" }), ...turnButtons()); | |
| 108 | const joining = lobby.hello.signin && !me; | |
| 109 | $("joinForm").hidden = $("forgeSignin").hidden = !joining; | |
| 110 | if (!joining) $("joinErr").textContent = ""; | |
| 111 | $("forgeSignin").href = `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`; | |
| 112 | $("waiting").textContent = st.queue.length ? String(st.queue.length) : ""; | |
| 113 | $("queue").replaceChildren(...st.queue.map((x) => { | |
| 114 | const mine = me && x.id === me.id; | |
| 115 | const li = queueEntry(el, x, Boolean(mine)); | |
| 116 | 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); } | |
| 117 | return li; | |
| 118 | })); | |
| 119 | $("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)" })])); | |
| 120 | if (me?.owner) { | |
| 121 | $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue"; | |
| 122 | $("pauseBtn").className = st.paused ? "go" : ""; | |
| 123 | $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused }); | |
| 124 | } | |
| 125 | $("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 })))) : [])); | |
| 126 | $("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 })))) : [])); | |
| 127 | renderCrew(me); | |
| 128 | $("say").hidden = !me || lobby.hello.muted || lobby.hello.banned; | |
| 129 | $("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." : ""; | |
| 130 | chatBox.classList.toggle("moderated", Boolean(me?.owner)); | |
| 131 | tickClock(); | |
| 132 | page.applyLock(); | |
| 133 | } | |
| 134 | /** The owner's view of the crew moderator: on/off, the rules, lines it hid, people it suggests muting. */ | |
| 135 | function renderCrew(me) { | |
| 136 | const c = lobby.crew; | |
| 137 | const box = $("crewLine"); | |
| 138 | if (!me?.owner || !c?.settings) return box.replaceChildren(el("p", { textContent: me?.owner ? "Waiting for the moderator's settings." : "" })); | |
| 139 | if (box.contains(doc.activeElement) && doc.activeElement.matches("textarea, input")) return; // do not drop what is being typed | |
| 140 | const perMinute = el("input", { type: "number", min: 1, max: 600, step: 1, value: c.settings.maxPerMinute, id: "crewMax", inputMode: "numeric" }); | |
| 141 | const rules = el("textarea", { value: c.settings.rules, rows: 3, maxLength: 2000, ariaLabel: "Room rules for the crew moderator" }); | |
| 142 | const item = (text, ...buttons) => el("div", { className: "item" }, el("span", { textContent: text }), ...buttons); | |
| 143 | box.replaceChildren( | |
| 144 | item(c.available ? (c.settings.enabled ? "On: every chat line is checked." : "Off.") : "No model reachable: nothing is checked.", | |
| 145 | button(c.settings.enabled ? "Turn off" : "Turn on", "", () => say({ type: "crew", settings: { enabled: !c.settings.enabled } }))), | |
| 146 | el("div", { className: "item" }, el("label", { htmlFor: "crewMax", textContent: "Most lines checked per minute" }), perMinute, | |
| 147 | button("Save", "", () => say({ type: "crew", settings: { maxPerMinute: Number(perMinute.value) } }))), | |
| 148 | rules, el("div", { className: "row" }, button("Save rules", "", () => say({ type: "crew", settings: { rules: rules.value } }))), | |
| 149 | ...c.hidden.map((h) => item(`Hidden: ${h.message.from?.name}: ${h.message.text} (${h.reason})`, button("Restore", "", () => say({ type: "restore", id: h.message.id })))), | |
| 150 | ...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 }))))); | |
| 151 | } | |
| 152 | /** Join: one field, one button. The answer sets the session cookie; the room is reopened to hear who you are now. */ | |
| 153 | $("joinForm").onsubmit = async (e) => { | |
| 154 | e.preventDefault(); | |
| 155 | const button = $("joinForm").querySelector("button"), err = $("joinErr"); | |
| 156 | button.disabled = true; | |
| 157 | try { | |
| 158 | const r = await fetch("/join", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: $("joinName").value.trim() }) }); | |
| 159 | const body = await r.json().catch(() => ({})); | |
| 160 | err.textContent = r.ok || (r.status === 409 && body.you) ? "" : body.error ?? `could not join (${r.status})`; | |
| 161 | if (!err.textContent) { $("joinName").value = ""; lobby.ws?.close(); } | |
| 162 | } catch { err.textContent = "could not reach the app; try again"; } | |
| 163 | button.disabled = false; | |
| 164 | }; | |
| 165 | const chatBox = $("chat"); | |
| 166 | function chatLine(m) { | |
| 167 | const me = lobby.hello?.you; | |
| 168 | const line = el("div", { className: m.from ? `line${me && m.from.id === me.id ? " me" : ""}` : "line sys", title: new Date(m.at).toLocaleTimeString() }); | |
| 169 | line.dataset.id = m.id; | |
| 170 | if (m.from) { line.dataset.from = m.from.id; line.dataset.name = m.from.name; line.append(el("b", { textContent: m.from.name })); } | |
| 171 | line.append(el("span", { textContent: m.text })); | |
| 172 | if (m.from && me?.owner) line.tabIndex = 0; | |
| 173 | return line; | |
| 174 | } | |
| 175 | // A new page gets the last lines of the chat; older ones come a page at a time, when asked for. | |
| 176 | const earlier = el("button", { type: "button", className: "earlier", textContent: "Earlier messages" }); | |
| 177 | earlier.onclick = () => { | |
| 178 | const first = chatBox.querySelector(".line[data-id]"); | |
| 179 | if (!first) return; | |
| 180 | earlier.disabled = true; | |
| 181 | say({ type: "history", before: Number(first.dataset.id) }); | |
| 182 | }; | |
| 183 | function showEarlier(more) { earlier.disabled = false; if (more) chatBox.prepend(earlier); else earlier.remove(); } | |
| 184 | function addOlder(lines, more) { | |
| 185 | const below = chatBox.scrollHeight - chatBox.scrollTop; // the reader stays on the line they were reading | |
| 186 | chatBox.prepend(...lines.map(chatLine)); | |
| 187 | chatBox.scrollTop = chatBox.scrollHeight - below; | |
| 188 | showEarlier(more); | |
| 189 | } | |
| 190 | function addChat(lines, replace = false) { | |
| 191 | const atEnd = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight < 40; | |
| 192 | if (replace) chatBox.replaceChildren(); | |
| 193 | chatBox.append(...lines.map(chatLine)); | |
| 194 | if (!replace) while (chatBox.querySelectorAll(".line").length > 200) chatBox.querySelector(".line").remove(); | |
| 195 | if (atEnd || replace) chatBox.scrollTop = chatBox.scrollHeight; | |
| 196 | if (!replace && page.tab() !== "chat") $("unread").textContent = String(Math.min(99, Number($("unread").textContent || 0) + lines.length)); | |
| 197 | } | |
| 198 | // Moderation on a phone: long-press a line (or right-click it, or Enter on it) for delete and mute. | |
| 199 | { | |
| 200 | let press = null, held = null; | |
| 201 | const open = (line) => { | |
| 202 | if (!lobby.hello?.you?.owner || !line?.dataset.from) return; | |
| 203 | held = line; line.classList.add("held"); | |
| 204 | $("modTitle").textContent = `${line.dataset.name} said`; | |
| 205 | $("modText").textContent = line.querySelector("span")?.textContent ?? ""; | |
| 206 | $("modMute").textContent = `Mute ${line.dataset.name}`; | |
| 207 | $("modBan").textContent = `Ban ${line.dataset.name}`; | |
| 208 | $("modMute").hidden = $("modBan").hidden = line.dataset.from === lobby.hello.you.id; | |
| 209 | $("modDlg").showModal(); | |
| 210 | nav.vibrate?.(10); | |
| 211 | }; | |
| 212 | chatBox.addEventListener("pointerdown", (e) => { | |
| 213 | const line = e.target.closest(".line"); if (!line?.dataset.from || !lobby.hello?.you?.owner) return; | |
| 214 | press = { x: e.clientX, y: e.clientY, timer: setTimeout(() => { press = null; open(line); }, 480) }; | |
| 215 | }); | |
| 216 | const cancel = () => { if (press) { clearTimeout(press.timer); press = null; } }; | |
| 217 | chatBox.addEventListener("pointermove", (e) => { if (press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) cancel(); }); | |
| 218 | for (const ev of ["pointerup", "pointercancel", "scroll"]) chatBox.addEventListener(ev, cancel); | |
| 219 | chatBox.addEventListener("contextmenu", (e) => { const line = e.target.closest(".line"); if (line?.dataset.from && lobby.hello?.you?.owner) { e.preventDefault(); cancel(); open(line); } }); | |
| 220 | chatBox.addEventListener("keydown", (e) => { if (e.key === "Enter" && e.target.classList?.contains("line")) open(e.target); }); | |
| 221 | $("modDlg").addEventListener("close", () => { | |
| 222 | const line = held; held = null; line?.classList.remove("held"); | |
| 223 | if (!line) return; | |
| 224 | if ($("modDlg").returnValue === "delete") say({ type: "delete", id: Number(line.dataset.id) }); | |
| 225 | if ($("modDlg").returnValue === "mute") say({ type: "mute", id: line.dataset.from, on: true }); | |
| 226 | 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 }); | |
| 227 | }); | |
| 228 | } | |
| 229 | function lobbyConnect() { | |
| 230 | const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`); | |
| 231 | lobby.ws = ws; | |
| 232 | ws.onopen = () => { lobby.retry = 500; }; | |
| 233 | ws.onmessage = (e) => { | |
| 234 | const m = JSON.parse(e.data); | |
| 235 | if (m.type === "ping") return say({ type: "pong" }); | |
| 236 | if (m.type === "status") { lobby.statusSeen = true; return m.status ? page.applyStatus(m.status) : page.noStatus(); } | |
| 237 | if (m.type === "hello") lobby.hello = m; | |
| 238 | else if (m.type === "state") { lobby.offset = m.now - Date.now(); lobby.state = m; } | |
| 239 | else if (m.type === "chat") return addChat(m.messages, true), showEarlier(m.more); | |
| 240 | else if (m.type === "history") return addOlder(m.messages, m.more); | |
| 241 | else if (m.type === "said") return addChat([m.message]); | |
| 242 | else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove(); | |
| 243 | else if (m.type === "muted") lobby.mutedList = m.muted; | |
| 244 | else if (m.type === "banned") lobby.bannedList = m.banned; | |
| 245 | else if (m.type === "words") page.words(m); | |
| 246 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; page.admin(saved); } | |
| 247 | else if (m.type === "crew") lobby.crew = m; | |
| 248 | else if (m.type === "error") return msg(m.error, true); | |
| 249 | renderTurn(); | |
| 250 | }; | |
| 251 | ws.onclose = () => { | |
| 252 | if (lobby.ws !== ws) return; | |
| 253 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back | |
| 254 | page.applyLock(); | |
| 255 | $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…"; | |
| 256 | setTimeout(lobbyConnect, lobby.retry); | |
| 257 | lobby.retry = Math.min(lobby.retry * 2, 8000); | |
| 258 | }; | |
| 259 | } | |
| 260 | $("say").onsubmit = (e) => { | |
| 261 | e.preventDefault(); | |
| 262 | const text = $("sayText").value.trim(); | |
| 263 | if (!text) return; | |
| 264 | say({ type: "post", text }); | |
| 265 | $("sayText").value = ""; | |
| 266 | chatBox.scrollTop = chatBox.scrollHeight; | |
| 267 | }; | |
| 268 | ||
| 269 | return { lobby, mayDrive, isOwner, say, serverNow, lobbyConnect, chatBox, renderTurn, button, tickClock }; | |
| 270 | } |
Software/so101/src/ui/lobby-panel.test.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { createRoom, minutes, ordinal, queueEntry, waitMinutes } from "./lobby-panel.js"; | |
| 3 | ||
| 4 | /** A stand-in for the page's el(): elements as plain trees, so the test needs no DOM. */ | |
| 5 | const el = (tag: string, props: Record<string, unknown> = {}, ...children: unknown[]) => ({ tag, ...props, children }); | |
| 6 | ||
| 7 | describe("the room's pure helpers", () => { | |
| 8 | test("a turn's clock reads m:ss and never goes negative", () => { | |
| 9 | expect(minutes(125_000)).toBe("2:05"); | |
| 10 | expect(minutes(-5)).toBe("0:00"); | |
| 11 | expect(minutes(1)).toBe("0:01"); | |
| 12 | }); | |
| 13 | ||
| 14 | test("places read as ordinals, the teens included", () => { | |
| 15 | expect([1, 2, 3, 4, 11, 12, 13, 21, 22, 112].map(ordinal)).toEqual(["1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "21st", "22nd", "112th"]); | |
| 16 | }); | |
| 17 | ||
| 18 | test("a wait is at least a minute, rounded up", () => { | |
| 19 | expect([0, 1, 60_000, 60_001, 150_000].map(waitMinutes)).toEqual([1, 1, 1, 2, 3]); | |
| 20 | }); | |
| 21 | ||
| 22 | test("a queue entry carries the name as text, so a name cannot be markup", () => { | |
| 23 | const name = `<img src=x onerror=alert(1)>`; | |
| 24 | const li = queueEntry(el as never, { id: "a", name, place: 2, waitMs: 90_000 }, false) as any; | |
| 25 | expect(li.className).toBe(""); | |
| 26 | expect(li.children.map((c: any) => c.textContent)).toEqual(["2.", name, "≤ 2 min"]); | |
| 27 | expect(li.children.every((c: any) => !("innerHTML" in c))).toBe(true); | |
| 28 | const me = queueEntry(el as never, { id: "a", name: "ann", place: 1, waitMs: 0 }, true) as any; | |
| 29 | expect(me.className).toBe("me"); | |
| 30 | expect(me.children[1].textContent).toBe("ann (you)"); | |
| 31 | }); | |
| 32 | }); | |
| 33 | ||
| 34 | describe("the room over /live", () => { | |
| 35 | /** A node that accepts whatever the room does to it. */ | |
| 36 | const node = (): any => new Proxy({ children: [], classList: { toggle() {}, add() {}, remove() {} }, style: { setProperty() {} }, dataset: {} }, { | |
| 37 | get: (t: any, k) => (k in t ? t[k] : (() => node())), | |
| 38 | set: (t: any, k, v) => ((t[k] = v), true), | |
| 39 | }); | |
| 40 | ||
| 41 | test("an error frame is shown with msg and does not stop the page rendering", () => { | |
| 42 | const sockets: any[] = []; | |
| 43 | const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, location: g.location }; | |
| 44 | g.WebSocket = class { readyState = 1; sent: string[] = []; constructor() { sockets.push(this); } send(m: string) { this.sent.push(m); } }; | |
| 45 | g.setInterval = () => 0; | |
| 46 | g.location = { protocol: "http:", host: "x", pathname: "/", search: "" }; | |
| 47 | try { | |
| 48 | const nodes = new Map<string, any>(), shown: [string, boolean | undefined][] = []; | |
| 49 | const page = { | |
| 50 | $: (id: string) => nodes.get(id) ?? (nodes.set(id, node()), nodes.get(id)), | |
| 51 | el: (tag: string, props: object = {}) => Object.assign(node(), { tag }, props), | |
| 52 | relayed: true, tab: () => "chat", showTab() {}, applyLock() {}, applyStatus() {}, noStatus() {}, words() {}, admin() {}, | |
| 53 | msg: (text: string, bad?: boolean) => void shown.push([text, bad]), | |
| 54 | }; | |
| 55 | const room = createRoom(page); | |
| 56 | room.lobbyConnect(); | |
| 57 | const ws = sockets[0]; | |
| 58 | ws.onmessage({ data: JSON.stringify({ type: "error", error: "that name is taken" }) }); | |
| 59 | expect(shown).toEqual([["that name is taken", true]]); | |
| 60 | ws.onmessage({ data: JSON.stringify({ type: "hello", signin: true, you: null }) }); | |
| 61 | ws.onmessage({ data: JSON.stringify({ type: "ping" }) }); | |
| 62 | expect(ws.sent).toEqual([JSON.stringify({ type: "pong" })]); | |
| 63 | expect(room.lobby.hello).not.toBeNull(); | |
| 64 | } finally { Object.assign(g, saved); } | |
| 65 | }); | |
| 66 | }); |
Software/so101/src/viewer.html +7 −240
| @@ -517,6 +517,7 @@ | ||
| 517 | 517 | import { cameraPlan, QUALITIES, samePlan } from "/ui/__VERSION__/camera-plan.js"; |
| 518 | 518 | import { bindSurface, canDrive, Driver, shape, UP } from "/ui/__VERSION__/drive.js"; |
| 519 | 519 | import { Frames } from "/ui/__VERSION__/frames.js"; |
| 520 | import { createRoom } from "/ui/__VERSION__/lobby-panel.js"; | |
| 520 | 521 | |
| 521 | 522 | const $ = (id) => document.getElementById(id); |
| 522 | 523 | const q = new URLSearchParams(location.search); |
| @@ -1553,10 +1554,12 @@ | ||
| 1553 | 1554 | // The page follows suit: the Controls tab appears on your turn. Everything here arrives on one socket. |
| 1554 | 1555 | let wordsSent = false; |
| 1555 | 1556 | $("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)); }; | |
| 1557 | const room = createRoom({ | |
| 1558 | $, el, relayed, msg, tab: () => tab, showTab, applyLock: () => applyLock(), applyStatus: (s) => applyStatus(s), noStatus: () => noStatus(), | |
| 1559 | words(m) { 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"}.`); } }, | |
| 1560 | admin: (saved) => fillAdmin(saved), | |
| 1561 | }); | |
| 1562 | const { lobby, mayDrive, isOwner, say, serverNow, lobbyConnect, chatBox, renderTurn, button } = room; | |
| 1560 | 1563 | let drove = false; |
| 1561 | 1564 | function explainLock() { |
| 1562 | 1565 | const me = lobby.hello?.you, down = linkNow === "offline", st = typeof status?.source === "string" && status.source.startsWith("simulated"); |
| @@ -1590,233 +1593,6 @@ | ||
| 1590 | 1593 | } |
| 1591 | 1594 | else if ($(`t-${tab}`).hidden) showTab(tab); |
| 1592 | 1595 | } |
| 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 | 1596 | // The owner's settings: filled from the server whenever they change, unless the owner is typing in the form. |
| 1821 | 1597 | function fillAdmin(saved) { |
| 1822 | 1598 | const form = $("adminForm"); |
| @@ -1833,15 +1609,6 @@ | ||
| 1833 | 1609 | document.activeElement?.blur(); |
| 1834 | 1610 | say({ type: "settings", set }); |
| 1835 | 1611 | }; |
| 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 | 1612 | // ---------------------------------------------------------------- 3D calibration |
| 1846 | 1613 | // The panel and its words are fetched the first time someone opens it: src/ui/calibration.js. |
| 1847 | 1614 | $("calib").onclick = async () => { |
new above
offline
msgis not in scope here: the module only destructures$, el, relayedfrompage(line 29). Usepage.msg(m.error, true), or destructure it.