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.

54 lines
1.5 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;
function displayWord(_word, end) {
let { word, reading } = _word;
p = document.createElement("p");
p.innerHTML = reading || word === reading ? (word === "" ? reading : `<ruby>${word}<rp>(</rp><rt>${reading}<rt/><rp>)</rp></ruby>`) : word;
if (end) {
div.append(p);
} else {
div.prepend(p);
}
div.scrollTop = div.offsetHeight;
}
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;
displayWord(data.word, true);
input.placeholder = waiting ? "Waiting for other players..." : `${data.next_char}`;
input.disabled = waiting;
if (!waiting) input.focus();
break;
case "history":
console.log(data);
data.words.forEach(word => {
displayWord(word, false);
})
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 = "";
}
});