Want to contribute? Fork me on Codeberg.org!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.3 KiB

ws = new WebSocket("ws://localhost:8080");
const div = document.querySelector("#shiritori");
const input = document.querySelector("#shiritori-input");
const players = document.querySelector("#shiritori-players");
let id = null;
ws.onmessage = e => {
const { event, data } = JSON.parse(e.data);
switch (event) {
case "greeting":
id = data.id;
break;
case "word":
let waiting = data.author === id;
p = document.createElement("p");
p.innerHTML = data.reading || data.word === data.reading ? (data.word === "" ? data.reading : `<ruby>${data.word}<rp>(</rp><rt>${data.reading}<rt/><rp>)</rp></ruby>`) : data.word;
div.appendChild(p);
div.scrollTop = div.offsetHeight;
input.placeholder = waiting ? "Waiting for other players..." : `${data.next_char}`;
input.disabled = waiting;
if (!waiting) input.focus();
break;
case "playerCount":
let otherPlayers = data.players - 1;
players.innerHTML = `${otherPlayers === 0 ? "No" : otherPlayers} other player${otherPlayers === 1 ? "" : "s"} online.`;
break;
case "error":
alert(data.message);
break;
}
}
input.addEventListener('keypress', e => {
if (e.key === 'Enter') {
ws.send(input.value);
input.value = "";
}
});