]> git.mar77i.info Git - hublib/blob - webroot/common.js
57ae142b7d7272eeb1ee6004b4d74ff75e5c3fe3
[hublib] / webroot / common.js
1 (function () {
2 var domconf_event_prefix = "event_";
3 function domconf(domobj, obj) {
4 var key;
5 for (key in obj) {
6 if (key.substring(0, domconf_event_prefix.length) == domconf_event_prefix) {
7 domobj.addEventListener(key.substring(domconf_event_prefix.length), obj[key]);
8 } else {
9 domobj.setAttribute(key, obj[key])
10 }
11 }
12 return domobj;
13 }
14
15 function tag(tag_name, obj) {
16 return domconf(document.createElement(tag_name), obj);
17 }
18
19 function HubClient(ws_uri, open, close, message) {
20 this.close = close.bind(this);
21 this.message = message.bind(this);
22 this.open = open.bind(this);
23 this.ws = domconf(
24 new WebSocket(
25 {"http:": "ws:", "https:": "wss:"}[window.location.protocol] +
26 "//" +
27 window.location.host +
28 ws_uri
29 ),
30 {
31 "event_close": this.close,
32 "event_message": this.message,
33 "event_open": this.open,
34 },
35 );
36 this.send = this.ws.send.bind(this.ws);
37 }
38
39 function write(output, msg) {
40 if (output.childNodes.length > 0) {
41 output.append(tag("br"));
42 }
43 if (typeof msg !== "string") {
44 msg = String(msg);
45 }
46 output.append(document.createTextNode(msg));
47 }
48
49 function setup(callback) {
50 domconf(
51 document,
52 {
53 "event_readystatechange": function (event) {
54 if (!event) {
55 event = window.event;
56 }
57 if (event.target.readyState !== "complete") {
58 return;
59 }
60 callback(event);
61 }
62 },
63 );
64 }
65
66 function make_key_event(callback) {
67 var wrapper = function (event) {
68 event = event || window.event;
69 callback(event, event.target || event.srcElement, event.code || event.key);
70 };
71 return wrapper;
72 }
73
74 function input_with_keydown_event(callback) {
75 return common.tag("input", {"event_keydown": make_key_event(callback)});
76 }
77
78 window.common = {
79 "tag": tag,
80 "HubClient": HubClient,
81 "write": write,
82 "setup": setup,
83 "input_with_keydown_event": input_with_keydown_event,
84 };
85 }());