formatted output
[mudsync.git] / data / web-static / js / mudsync.js
1 /*
2 ;;; Mudsync --- Live hackable MUD
3 ;;; Copyright © 2017 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;;
5 ;;; This file is part of Mudsync.
6 ;;;
7 ;;; Mudsync is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or
10 ;;; (at your option) any later version.
11 ;;;
12 ;;; Mudsync is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;;; General Public License for more details.
16 ;;;
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with Mudsync.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 function displayMessage(data, self_sent) {
22     var new_entry = document.createElement("div");
23     var stream_metabox = document.getElementById("stream-metabox");
24     var should_scroll = false;
25     if(stream_metabox.scrollTop === (stream_metabox.scrollHeight
26                                      - stream_metabox.offsetHeight)) {
27         should_scroll = true;
28     }
29     if (self_sent) {
30         new_entry.setAttribute("class", "stream-entry self-sent");
31         document.getElementById("main-input").value = "";
32     } else {
33         new_entry.setAttribute("class", "stream-entry");
34     }
35     new_entry.innerHTML = data;
36     document.getElementById("stream").appendChild(new_entry);
37     if (should_scroll) {
38         stream_metabox.scrollTop = stream_metabox.scrollHeight;
39     }
40 }
41
42 function installWebsocket() {
43     // TODO: Don't hardcode the websocket path; pull it from the DOM
44     var address = "ws://".concat(window.location.hostname, ":", window.location.port);
45     var ws = new WebSocket(address);
46     ws.onmessage = function(evt) {
47         displayMessage(evt.data, false);
48     };
49     ws.onopen = function() {
50         console.log("connected");
51     };
52     ws.onclose = function () {
53         console.log("closed websocket");
54     };
55     installUIHooks(ws);
56 }
57
58 function installUIHooks(ws) {
59     var input = document.getElementById("main-input");
60     input.onkeypress = function(e) {
61         if (!e) e = window.event;
62         var keyCode = e.keyCode || e.which;
63         if (keyCode == '13') {
64             var input_val = input.value;
65             displayMessage("> ".concat(input_val), true);
66             sendMessageToServer(ws, input_val);
67         }
68     }
69 }
70
71 function sendMessageToServer(ws, data) {
72     ws.send(data);
73 }
74
75
76 window.onload = function () {
77     installWebsocket();
78 }