Ooui-tws-port/Ooui/Client.js

102 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-06-13 01:24:30 +00:00
2017-06-13 01:50:48 +00:00
// Create WebSocket connection.
2017-06-13 02:54:47 +00:00
const socket = new WebSocket ("ws://localhost:8080" + rootElementPath, "ooui-1.0");
2017-06-13 01:24:30 +00:00
2017-06-13 04:50:15 +00:00
console.log("WebSocket created");
const nodes = {}
function getNode (id) {
switch (id) {
case "window": return window;
case "document": return document;
case "document.body": return document.body;
default: return nodes[id];
}
}
function msgCreate (m) {
const id = m.id;
2017-06-13 07:03:01 +00:00
const tagName = m.k;
2017-06-13 04:50:15 +00:00
const node = tagName === "text" ?
document.createTextNode ("") :
document.createElement (tagName);
if (tagName !== "text")
node.id = id;
nodes[id] = node;
2017-06-13 07:51:24 +00:00
console.log ("Created node", node);
2017-06-13 04:50:15 +00:00
}
function msgSet (m) {
const id = m.id;
const node = getNode (id);
if (!node) {
2017-06-13 07:51:24 +00:00
console.error ("Unknown node id", m);
2017-06-13 04:50:15 +00:00
return;
}
node[m.k] = m.v;
2017-06-13 07:51:24 +00:00
console.log ("Set property", node, m.k, m.v);
2017-06-13 04:50:15 +00:00
}
function msgCall (m) {
const id = m.id;
const node = getNode (id);
if (!node) {
2017-06-13 07:51:24 +00:00
console.error ("Unknown node id", m);
2017-06-13 04:50:15 +00:00
return;
}
const f = node[m.k];
console.log ("Call", node, f, m.v);
f.apply (node, m.v);
}
function processMessage (m) {
switch (m.m) {
2017-06-13 07:03:01 +00:00
case "nop":
break;
case "create":
2017-06-13 04:50:15 +00:00
msgCreate (m);
break;
2017-06-13 07:03:01 +00:00
case "set":
2017-06-13 04:50:15 +00:00
msgSet (m);
break;
2017-06-13 07:03:01 +00:00
case "call":
2017-06-13 04:50:15 +00:00
msgCall (m);
break;
default:
console.error ("Unknown message type", m.m, m);
}
}
function fixupValue (v) {
if (Array.isArray (v)) {
for (x in v) {
v[x] = fixupValue (v[x]);
}
return v;
}
else if (typeof v === 'string' || v instanceof String) {
2017-06-13 07:03:01 +00:00
if ((v.length >= 2) && (v[0] === "\u2999") && (v[1] === "n")) {
// console.log("V", v);
const id = v.substr(1);
// console.log("ID", id);
return getNode (id);
2017-06-13 04:50:15 +00:00
}
}
return v;
}
2017-06-13 01:24:30 +00:00
2017-06-13 01:50:48 +00:00
// Connection opened
socket.addEventListener('open', function (event) {
2017-06-13 04:50:15 +00:00
console.log("WebSocket opened");
2017-06-13 01:50:48 +00:00
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
2017-06-13 04:50:15 +00:00
const message = JSON.parse (event.data);
message.v = fixupValue (message.v);
console.log('Message from server', message);
processMessage (message);
2017-06-13 01:50:48 +00:00
});