class Configuration { constructor(game, user) { this.game = game; this.user = user; } static fromFragment() { const config = { "game": "testing", "user": "test_user", }; const rawHash = window.location.hash; if (rawHash) { const hash = rawHash.substr(1, rawHash.length).split(","); for (let i in hash) { let elements = hash[i].split(":"); if (elements.length != 2) { continue; } config[elements[0]] = elements[1]; } } return new Configuration(config.game, config.user); } } class Messages { static config(game, user) { return JSON.stringify({ "tag": "config", "game": game, "user": user, }); } static post(author, content) { return JSON.stringify({ "tag": "post", "author": author, "content": content, }); } } class Socket { constructor() { var loc = window.location, new_uri; if (loc.protocol === "https:") { new_uri = "wss:"; } else { new_uri = "ws:"; } new_uri += "//" + loc.host; new_uri += loc.pathname + "socket"; this.socket = new WebSocket(new_uri); } onOpen(func) { this.socket.addEventListener("open", func); } onMessage(func) { this.socket.addEventListener("message", func); } config(game, user) { this.socket.send(Messages.config(game, user)); } post(author, content) { this.socket.send(Messages.post(author, content)); } } window.onload = function() { const config = Configuration.fromFragment(); const socket = new Socket(); $("#loggedin").text(`logged in as "${config.user}"`); $("#gamename").text(`playing in "${config.game}"`); socket.onOpen(function (event) { console.log("Connected to server!"); socket.config(config.game, config.user); }); socket.onMessage(function (event) { msg = JSON.parse(event.data); var chat = $(".messages"); chat.append(`
${msg.author}: ${msg.content}
`); chat.animate({scrollTop: chat.prop('scrollHeight')}); }); $('#chatbox').on('keypress', function (e) { if (e.which === 13) { $(this).attr("disabled", "disabled"); socket.post(config.user, $('#chatbox').val()); $('#chatbox').val(''); $(this).removeAttr("disabled"); } }); };