main.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. class Configuration {
  2. constructor(game, user) {
  3. this.game = game;
  4. this.user = user;
  5. }
  6. static fromFragment() {
  7. const config = {
  8. "game": "testing",
  9. "user": "test_user",
  10. };
  11. const rawHash = window.location.hash;
  12. if (rawHash) {
  13. const hash = rawHash.substr(1, rawHash.length).split(",");
  14. for (let i in hash) {
  15. let elements = hash[i].split(":");
  16. if (elements.length != 2) {
  17. continue;
  18. }
  19. config[elements[0]] = elements[1];
  20. }
  21. }
  22. return new Configuration(config.game, config.user);
  23. }
  24. }
  25. class Messages {
  26. static config(game, user) {
  27. return JSON.stringify({
  28. "tag": "config",
  29. "game": game,
  30. "user": user,
  31. });
  32. }
  33. static post(author, content) {
  34. return JSON.stringify({
  35. "tag": "post",
  36. "author": author,
  37. "content": content,
  38. });
  39. }
  40. }
  41. class Socket {
  42. constructor() {
  43. var loc = window.location, new_uri;
  44. if (loc.protocol === "https:") {
  45. new_uri = "wss:";
  46. } else {
  47. new_uri = "ws:";
  48. }
  49. new_uri += "//" + loc.host;
  50. new_uri += loc.pathname + "socket";
  51. this.socket = new WebSocket(new_uri);
  52. }
  53. onOpen(func) {
  54. this.socket.addEventListener("open", func);
  55. }
  56. onMessage(func) {
  57. this.socket.addEventListener("message", func);
  58. }
  59. config(game, user) {
  60. this.socket.send(Messages.config(game, user));
  61. }
  62. post(author, content) {
  63. this.socket.send(Messages.post(author, content));
  64. }
  65. }
  66. window.onload = function() {
  67. const config = Configuration.fromFragment();
  68. const socket = new Socket();
  69. $("#loggedin").text(`logged in as "${config.user}"`);
  70. $("#gamename").text(`playing in "${config.game}"`);
  71. socket.onOpen(function (event) {
  72. console.log("Connected to server!");
  73. socket.config(config.game, config.user);
  74. });
  75. socket.onMessage(function (event) {
  76. msg = JSON.parse(event.data);
  77. var chat = $(".messages");
  78. chat.append(`<div class="msg"><span class="author">${msg.author}:</span> ${msg.content}</div>`);
  79. chat.animate({scrollTop: chat.prop('scrollHeight')});
  80. });
  81. $('#chatbox').on('keypress', function (e) {
  82. if (e.which === 13) {
  83. $(this).attr("disabled", "disabled");
  84. socket.post(config.user, $('#chatbox').val());
  85. $('#chatbox').val('');
  86. $(this).removeAttr("disabled");
  87. }
  88. });
  89. };