sending messages to the server from websockets works
[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) {
22     var new_entry = document.createElement("div");
23     var new_text = document.createTextNode(data);
24     var stream_metabox = document.getElementById("stream-metabox");
25     var should_scroll = false;
26     if(stream_metabox.scrollTop === (stream_metabox.scrollHeight
27                                      - stream_metabox.offsetHeight)) {
28         should_scroll = true;
29     }
30     document.getElementById("main-input").value = "";
31     new_entry.setAttribute("class", "stream-entry");
32     new_entry.appendChild(new_text);
33     document.getElementById("stream").appendChild(new_entry);
34     if (should_scroll) {
35         stream_metabox.scrollTop = stream_metabox.scrollHeight;
36     }
37 }
38
39 function installWebsocket() {
40     // TODO: Don't hardcode the websocket path; pull it from the DOM
41     var ws = new WebSocket("ws://127.0.0.1:8888");
42     ws.onmessage = function(evt) {
43         displayMessage(evt.data);
44     };
45     ws.onopen = function() {
46         console.log("connected");
47         ws.send("Hello, there!");
48     };
49     ws.onclose = function () {
50         console.log("closed websocket");
51     };
52     installUIHooks(ws);
53 }
54
55 function installUIHooks(ws) {
56     var input = document.getElementById("main-input");
57     input.onkeypress = function(e) {
58         if (!e) e = window.event;
59         var keyCode = e.keyCode || e.which;
60         if (keyCode == '13') {
61             sendMessageToServer(ws, input.value);
62         }
63     }
64 }
65
66 function sendMessageToServer(ws, data) {
67     ws.send(data);
68 }
69
70
71 window.onload = function () {
72     installWebsocket();
73 }