]> git.mar77i.info Git - hublib/blob - webroot/first/index.js
big cleanup and refactoring #1
[hublib] / webroot / first / index.js
1 (function () {
2 "use strict";
3 var input_div = null;
4
5 function write(msg) {
6 common.write(
7 input_div === null ? document.body : input_div.previousSibling, msg
8 );
9 }
10
11 function change_name_button(hub) {
12 var btn = common.tag(
13 "button",
14 {
15 "event_click": function () {
16 setup_change_name(hub);
17 }
18 }
19 );
20 btn.append(document.createTextNode("change name"));
21 return btn;
22 }
23
24 function setup_chat(hub) {
25 input_div = common.tag("div");
26 input_div.append(
27 common.input_with_keydown_event(
28 function (event, target, keycode) {
29 if (keycode !== "Enter" && keycode !== "NumpadEnter") {
30 return;
31 }
32 hub.send(JSON.stringify({"data": target.value}));
33 target.value = "";
34 }
35 )
36 );
37 input_div.append(document.createTextNode(" "));
38 input_div.append(change_name_button(hub));
39
40 document.body.append(common.tag("div"));
41 document.body.append(input_div);
42 }
43
44 function setup_change_name(hub) {
45 var div = common.tag("div");
46 div.append(document.createTextNode("Enter name: "));
47 div.append(
48 common.input_with_keydown_event(
49 function (event, target, keycode) {
50 if (keycode !== "Enter" && keycode !== "NumpadEnter") {
51 return;
52 }
53 if (input_div.childNodes[0] !== input_div.children[0]) {
54 input_div.childNodes[0].remove();
55 }
56 input_div.insertBefore(
57 document.createTextNode(target.value + " "), input_div.children[0]
58 );
59 hub.send(JSON.stringify({"action": "set_name", "name": target.value}));
60 div.remove();
61 input_div.style.display = "";
62 input_div.children[0].focus();
63 }
64 )
65 )
66 document.body.append(div);
67 input_div.style.display = "none";
68 div.children[0].focus();
69 }
70
71 function open() {
72 setup_chat(this);
73 write("connected to " + ws_uri);
74 setup_change_name(this);
75 }
76
77 function close() {
78 write("connection lost");
79 if (input_div !== null) {
80 input_div.remove();
81 input_div = null;
82 }
83 }
84
85 function message(msg) {
86 var obj = JSON.parse(msg.data);
87 if (obj.action === "join" || obj.action === "leave") {
88 write("[action]: " + obj.name + " " + obj.action + "s");
89 } else if (obj.action == "set_name") {
90 write(
91 "[action]: " +
92 obj.old_name +
93 " changes name to " +
94 obj.name
95 );
96 } else if (obj.hasOwnProperty("data")) {
97 write(obj.name + ": " + obj.data);
98 }
99 }
100
101 common.setup(function () {new common.HubClient(ws_uri, open, close, message)});
102 })();