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 : `${word}(${reading})`) : 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 = ""; } });