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, delay) { let { word, reading } = _word; p = document.createElement("p"); p.innerHTML = reading || word === reading ? (word === "" ? reading : `${word}(${reading})`) : word; if (delay != 0) { p.style.animationDelay = `${delay}s`; } 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, 0); input.placeholder = waiting ? "Waiting for other players..." : `${data.next_mora}…`; input.disabled = waiting; if (!waiting) input.focus(); break; case "history": console.log(data); for (let i = 0; i < data.words.length; i++) { displayWord(data.words[i], false, 0.1 * i); } 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 = ""; } });