X-Git-Url: https://git.mar77i.info/?a=blobdiff_plain;f=webroot%2Ffirst%2Findex.js;fp=webroot%2Ffirst%2Findex.js;h=8cae34e6e39a60df7b28a53fafb70fe958de9d5a;hb=6128e895bc2a5da5fe645cc9a7ad74ac75af4f6b;hp=0000000000000000000000000000000000000000;hpb=66e1cc7886b1ce7092281a43b9ee7969366e6835;p=hublib diff --git a/webroot/first/index.js b/webroot/first/index.js new file mode 100644 index 0000000..8cae34e --- /dev/null +++ b/webroot/first/index.js @@ -0,0 +1,97 @@ +(function () { + "use strict"; + var input_div = null; + + function write(msg) { + common.write(input_div.previousSibling, msg); + } + + function change_name_button(hub) { + var btn = common.tag( + "button", + { + "event_click": function () { + setup_change_name(hub); + } + } + ); + btn.append(document.createTextNode("change name")); + return btn; + } + + function setup_chat(hub) { + input_div = common.tag("div"); + input_div.append( + common.input_with_keydown_event( + function (event, target, keycode) { + if (keycode !== "Enter" && keycode !== "NumpadEnter") { + return; + } + hub.send(JSON.stringify({"data": target.value})); + target.value = ""; + } + ) + ); + input_div.append(document.createTextNode(" ")); + input_div.append(change_name_button(hub)); + + document.body.append(common.tag("div")); + document.body.append(input_div); + } + + function setup_change_name(hub) { + var div = common.tag("div"); + div.append(document.createTextNode("Enter name: ")); + div.append( + common.input_with_keydown_event( + function (event, target, keycode) { + if (keycode !== "Enter" && keycode !== "NumpadEnter") { + return; + } + if (input_div.childNodes[0] !== input_div.children[0]) { + input_div.childNodes[0].remove(); + } + input_div.insertBefore( + document.createTextNode(target.value + " "), input_div.children[0] + ); + hub.send(JSON.stringify({"action": "set_name", "name": target.value})); + div.remove(); + input_div.style.display = ""; + input_div.children[0].focus(); + } + ) + ) + document.body.append(div); + input_div.style.display = "none"; + div.children[0].focus(); + } + + function open() { + setup_chat(this); + write("connected to " + ws_uri); + setup_change_name(this); + } + + function close() { + write("connection lost"); + input_div.remove(); + } + + function message(msg) { + var obj = JSON.parse(msg.data); + if (obj.action === "join" || obj.action === "leave") { + write("[action]: " + obj.name + " " + obj.action + "s"); + } else if (obj.action == "set_name") { + write( + "[action]: " + + obj.old_name + + " changes name to " + + obj.name + ); + } else if (obj.hasOwnProperty("data")) { + write(obj.name + ": " + obj.data); + } + } + + common.setup(function () {new common.HubClient(ws_uri, open, close, message)}); +})();