major changes, leaving it at that
This commit is contained in:
1 parent
8cb4c3556b
commit
b55251cfc5
16 files changed
+3280
-302
No files matched your search
+182
@@ -0,0 +1,182 @@
|
||||
// Shared browser networking for every page.
|
||||
//
|
||||
// The server is authoritative. Pages send intents (JOIN_ROOM, CREATE_ROOM,
|
||||
// PING, ...) and render what the server sends back. This file only knows about
|
||||
// transport: connection, reconnection, heartbeat, and per-tab identity.
|
||||
|
||||
const wsProtocol = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
export const WS_URL = `${wsProtocol}//${location.host}/ws`;
|
||||
|
||||
export function getClientId() {
|
||||
let clientId = sessionStorage.getItem("clientId");
|
||||
|
||||
if (!clientId) {
|
||||
clientId =
|
||||
crypto.randomUUID?.() ??
|
||||
Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
sessionStorage.setItem("clientId", clientId);
|
||||
}
|
||||
|
||||
return clientId;
|
||||
}
|
||||
|
||||
export const student = {
|
||||
get() {
|
||||
return {
|
||||
name: sessionStorage.getItem("playerName") ?? "",
|
||||
code: sessionStorage.getItem("roomCode") ?? "",
|
||||
clientId: getClientId(),
|
||||
};
|
||||
},
|
||||
|
||||
save(name, code) {
|
||||
sessionStorage.setItem("playerName", name);
|
||||
sessionStorage.setItem("roomCode", code);
|
||||
},
|
||||
|
||||
clear() {
|
||||
sessionStorage.removeItem("playerName");
|
||||
sessionStorage.removeItem("roomCode");
|
||||
},
|
||||
};
|
||||
|
||||
export const teacher = {
|
||||
get() {
|
||||
return {
|
||||
code: sessionStorage.getItem("teacherCode") ?? "",
|
||||
token: sessionStorage.getItem("teacherToken") ?? "",
|
||||
};
|
||||
},
|
||||
|
||||
save(code, token) {
|
||||
sessionStorage.setItem("teacherCode", code);
|
||||
sessionStorage.setItem("teacherToken", token);
|
||||
},
|
||||
|
||||
clear() {
|
||||
sessionStorage.removeItem("teacherCode");
|
||||
sessionStorage.removeItem("teacherToken");
|
||||
},
|
||||
};
|
||||
|
||||
// Tell the server which student this tab belongs to.
|
||||
export function joinStudentRoom(send) {
|
||||
const { name, code, clientId } = student.get();
|
||||
|
||||
if (!name || !code) {
|
||||
location.href = "/";
|
||||
return false;
|
||||
}
|
||||
|
||||
return send({ type: "JOIN_ROOM", name, code, clientId });
|
||||
}
|
||||
|
||||
// Reclaim a room the teacher already created in this tab.
|
||||
export function resumeTeacherRoom(send) {
|
||||
const { code, token } = teacher.get();
|
||||
|
||||
if (!code || !token) return false;
|
||||
|
||||
return send({ type: "RESUME_TEACHER", code, token });
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket and keep it open.
|
||||
*
|
||||
* Options:
|
||||
* onMessage(data) called for every non-PONG server message
|
||||
* onStatus(status) "connecting" | "connected" | "disconnected" |
|
||||
* "error" | "replaced"
|
||||
* onOpen(send) called after each successful (re)connection, so the page
|
||||
* can re-announce who it is
|
||||
*
|
||||
* Returns { send, close } where send() returns false when the socket is not
|
||||
* ready instead of throwing.
|
||||
*/
|
||||
export function createConnection({ onMessage, onStatus = () => {}, onOpen } = {}) {
|
||||
let socket = null;
|
||||
let heartbeat = null;
|
||||
let reconnectTimer = null;
|
||||
let reconnectDelay = 1000;
|
||||
let unloading = false;
|
||||
|
||||
window.addEventListener("beforeunload", () => {
|
||||
unloading = true;
|
||||
});
|
||||
|
||||
function send(message) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return false;
|
||||
socket.send(JSON.stringify(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
function connect() {
|
||||
onStatus("connecting");
|
||||
|
||||
const ws = new WebSocket(WS_URL);
|
||||
socket = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
reconnectDelay = 1000;
|
||||
|
||||
clearInterval(heartbeat);
|
||||
heartbeat = setInterval(() => {
|
||||
if (socket?.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: "PING" }));
|
||||
}
|
||||
}, 25000);
|
||||
|
||||
onStatus("connected");
|
||||
onOpen?.(send);
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch {
|
||||
console.warn("Ignored a non-JSON server message");
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "PONG") return;
|
||||
onMessage?.(data);
|
||||
};
|
||||
|
||||
ws.onclose = (event) => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
socket = null;
|
||||
clearInterval(heartbeat);
|
||||
heartbeat = null;
|
||||
|
||||
// 4000 = the server found a newer connection for this identity. Do not
|
||||
// reconnect, or two tabs will keep taking the room from each other.
|
||||
if (event.code === 4000) {
|
||||
onStatus("replaced");
|
||||
return;
|
||||
}
|
||||
|
||||
onStatus("disconnected");
|
||||
|
||||
if (unloading) return;
|
||||
|
||||
reconnectTimer = setTimeout(connect, reconnectDelay);
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, 10000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
if (socket === ws) onStatus("error");
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
|
||||
return { send };
|
||||
}
|
||||
Reference in new issue
Block a user