123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- 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(`<div class="msg"><span class="author">${msg.author}:</span> ${msg.content}</div>`);
- 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");
- }
- });
- };
|