@mml-io/networked-dom-web 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +75 -61
- package/build/index.js.map +2 -2
- package/package.json +2 -2
- package/src/NetworkedDOMWebsocket.ts +85 -69
package/build/index.js
CHANGED
|
@@ -90,24 +90,6 @@ var NetworkedDOMWebsocketStatus = /* @__PURE__ */ ((NetworkedDOMWebsocketStatus2
|
|
|
90
90
|
NetworkedDOMWebsocketStatus2[NetworkedDOMWebsocketStatus2["Disconnected"] = 3] = "Disconnected";
|
|
91
91
|
return NetworkedDOMWebsocketStatus2;
|
|
92
92
|
})(NetworkedDOMWebsocketStatus || {});
|
|
93
|
-
function isHTMLElement(node) {
|
|
94
|
-
if (node instanceof HTMLElement) {
|
|
95
|
-
return true;
|
|
96
|
-
}
|
|
97
|
-
if (!this.parentElement.ownerDocument.defaultView) {
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;
|
|
101
|
-
}
|
|
102
|
-
function isText(node) {
|
|
103
|
-
if (node instanceof Text) {
|
|
104
|
-
return true;
|
|
105
|
-
}
|
|
106
|
-
if (!this.parentElement.ownerDocument.defaultView) {
|
|
107
|
-
return false;
|
|
108
|
-
}
|
|
109
|
-
return node instanceof this.parentElement.ownerDocument.defaultView.Text;
|
|
110
|
-
}
|
|
111
93
|
var NetworkedDOMWebsocket = class {
|
|
112
94
|
constructor(url, websocketFactory, parentElement, timeCallback, statusUpdateCallback) {
|
|
113
95
|
this.idToElement = /* @__PURE__ */ new Map();
|
|
@@ -136,6 +118,24 @@ var NetworkedDOMWebsocket = class {
|
|
|
136
118
|
this.statusUpdateCallback(status);
|
|
137
119
|
}
|
|
138
120
|
}
|
|
121
|
+
isHTMLElement(node) {
|
|
122
|
+
if (node instanceof HTMLElement) {
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
if (!this.parentElement.ownerDocument.defaultView) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;
|
|
129
|
+
}
|
|
130
|
+
isText(node) {
|
|
131
|
+
if (node instanceof Text) {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
if (!this.parentElement.ownerDocument.defaultView) {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
return node instanceof this.parentElement.ownerDocument.defaultView.Text;
|
|
138
|
+
}
|
|
139
139
|
createWebsocketWithTimeout(timeout) {
|
|
140
140
|
return new Promise((resolve, reject) => {
|
|
141
141
|
const timeoutId = setTimeout(() => {
|
|
@@ -219,47 +219,42 @@ var NetworkedDOMWebsocket = class {
|
|
|
219
219
|
handleIncomingWebsocketMessage(event) {
|
|
220
220
|
const messages = JSON.parse(event.data);
|
|
221
221
|
for (const message of messages) {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
this.setStatus(1 /* Connected */);
|
|
235
|
-
if (this.currentRoot) {
|
|
236
|
-
this.currentRoot.remove();
|
|
237
|
-
this.currentRoot = null;
|
|
238
|
-
this.elementToId.clear();
|
|
239
|
-
this.idToElement.clear();
|
|
240
|
-
}
|
|
241
|
-
const element = this.handleNewElement(message.snapshot);
|
|
242
|
-
if (!element) {
|
|
243
|
-
throw new Error("Snapshot element not created");
|
|
222
|
+
switch (message.type) {
|
|
223
|
+
case "error":
|
|
224
|
+
console.error("Error from server", message);
|
|
225
|
+
break;
|
|
226
|
+
case "warning":
|
|
227
|
+
console.warn("Warning from server", message);
|
|
228
|
+
break;
|
|
229
|
+
default: {
|
|
230
|
+
if (message.documentTime) {
|
|
231
|
+
if (this.timeCallback) {
|
|
232
|
+
this.timeCallback(message.documentTime);
|
|
233
|
+
}
|
|
244
234
|
}
|
|
245
|
-
|
|
246
|
-
|
|
235
|
+
switch (message.type) {
|
|
236
|
+
case "snapshot":
|
|
237
|
+
this.handleSnapshot(message);
|
|
238
|
+
break;
|
|
239
|
+
case "attributeChange":
|
|
240
|
+
this.handleAttributeChange(message);
|
|
241
|
+
break;
|
|
242
|
+
case "childrenChanged":
|
|
243
|
+
this.handleChildrenChanged(message);
|
|
244
|
+
break;
|
|
245
|
+
case "textChanged":
|
|
246
|
+
this.handleTextChanged(message);
|
|
247
|
+
break;
|
|
248
|
+
case "ping":
|
|
249
|
+
this.send({
|
|
250
|
+
type: "pong",
|
|
251
|
+
pong: message.ping
|
|
252
|
+
});
|
|
253
|
+
break;
|
|
254
|
+
default:
|
|
255
|
+
console.warn("unknown message type", message);
|
|
256
|
+
break;
|
|
247
257
|
}
|
|
248
|
-
this.currentRoot = element;
|
|
249
|
-
this.parentElement.append(element);
|
|
250
|
-
} else if (message.type === "attributeChange") {
|
|
251
|
-
this.handleAttributeChange(message);
|
|
252
|
-
} else if (message.type === "childrenChanged") {
|
|
253
|
-
this.handleChildrenChanged(message);
|
|
254
|
-
} else if (message.type === "textChanged") {
|
|
255
|
-
this.handleTextChanged(message);
|
|
256
|
-
} else if (message.type === "ping") {
|
|
257
|
-
this.send({
|
|
258
|
-
type: "pong",
|
|
259
|
-
pong: message.ping
|
|
260
|
-
});
|
|
261
|
-
} else {
|
|
262
|
-
console.warn("unknown message type", message);
|
|
263
258
|
}
|
|
264
259
|
}
|
|
265
260
|
}
|
|
@@ -308,7 +303,7 @@ var NetworkedDOMWebsocket = class {
|
|
|
308
303
|
if (!node) {
|
|
309
304
|
throw new Error("No node found for textChanged message");
|
|
310
305
|
}
|
|
311
|
-
if (!isText(node)) {
|
|
306
|
+
if (!this.isText(node)) {
|
|
312
307
|
throw new Error("Node for textChanged message is not a Text node");
|
|
313
308
|
}
|
|
314
309
|
node.textContent = text;
|
|
@@ -326,7 +321,7 @@ var NetworkedDOMWebsocket = class {
|
|
|
326
321
|
if (!parent.isConnected) {
|
|
327
322
|
console.error("Parent is not connected", parent);
|
|
328
323
|
}
|
|
329
|
-
if (!isHTMLElement(parent)) {
|
|
324
|
+
if (!this.isHTMLElement(parent)) {
|
|
330
325
|
throw new Error("Parent is not an HTMLElement (that supports children)");
|
|
331
326
|
}
|
|
332
327
|
let previousElement;
|
|
@@ -359,7 +354,7 @@ var NetworkedDOMWebsocket = class {
|
|
|
359
354
|
this.elementToId.delete(childElement);
|
|
360
355
|
this.idToElement.delete(removedNode);
|
|
361
356
|
parent.removeChild(childElement);
|
|
362
|
-
if (isHTMLElement(childElement)) {
|
|
357
|
+
if (this.isHTMLElement(childElement)) {
|
|
363
358
|
this.removeChildElementIds(childElement);
|
|
364
359
|
}
|
|
365
360
|
}
|
|
@@ -377,6 +372,25 @@ var NetworkedDOMWebsocket = class {
|
|
|
377
372
|
this.removeChildElementIds(child);
|
|
378
373
|
}
|
|
379
374
|
}
|
|
375
|
+
handleSnapshot(message) {
|
|
376
|
+
this.backoffTime = startingBackoffTimeMilliseconds;
|
|
377
|
+
this.setStatus(1 /* Connected */);
|
|
378
|
+
if (this.currentRoot) {
|
|
379
|
+
this.currentRoot.remove();
|
|
380
|
+
this.currentRoot = null;
|
|
381
|
+
this.elementToId.clear();
|
|
382
|
+
this.idToElement.clear();
|
|
383
|
+
}
|
|
384
|
+
const element = this.handleNewElement(message.snapshot);
|
|
385
|
+
if (!element) {
|
|
386
|
+
throw new Error("Snapshot element not created");
|
|
387
|
+
}
|
|
388
|
+
if (!this.isHTMLElement(element)) {
|
|
389
|
+
throw new Error("Snapshot element is not an HTMLElement");
|
|
390
|
+
}
|
|
391
|
+
this.currentRoot = element;
|
|
392
|
+
this.parentElement.append(element);
|
|
393
|
+
}
|
|
380
394
|
handleAttributeChange(message) {
|
|
381
395
|
const { nodeId, attribute, newValue } = message;
|
|
382
396
|
if (nodeId === void 0 || nodeId === null) {
|
|
@@ -385,7 +399,7 @@ var NetworkedDOMWebsocket = class {
|
|
|
385
399
|
}
|
|
386
400
|
const element = this.idToElement.get(nodeId);
|
|
387
401
|
if (element) {
|
|
388
|
-
if (isHTMLElement(element)) {
|
|
402
|
+
if (this.isHTMLElement(element)) {
|
|
389
403
|
if (newValue === null) {
|
|
390
404
|
element.removeAttribute(attribute);
|
|
391
405
|
} else {
|
package/build/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../src/DOMSanitizer.ts", "../src/NetworkedDOMWebsocket.ts"],
|
|
4
|
-
"sourcesContent": ["export * from \"./NetworkedDOMWebsocket\";\nexport * from \"./DOMSanitizer\";\n", "export class DOMSanitizer {\n static sanitise(node: HTMLElement) {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.IsValidAttributeName(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n if (node.nodeName === \"SCRIPT\") {\n // set text to empty string\n node.innerText = \"\";\n } else {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.shouldAcceptAttribute(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n for (let i = 0; i < node.childNodes.length; i++) {\n DOMSanitizer.sanitise(node.childNodes[i] as HTMLElement);\n }\n }\n }\n\n static IsASCIIDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n }\n\n static IsASCIIAlpha(c: string) {\n return c >= \"a\" && c <= \"z\";\n }\n\n static IsValidAttributeName(characters: string): boolean {\n const c = characters[0];\n if (!(DOMSanitizer.IsASCIIAlpha(c) || c === \":\" || c === \"_\")) {\n return false;\n }\n\n for (let i = 1; i < characters.length; i++) {\n const c = characters[i];\n if (\n !(\n DOMSanitizer.IsASCIIDigit(c) ||\n DOMSanitizer.IsASCIIAlpha(c) ||\n c === \":\" ||\n c === \"_\" ||\n c === \"-\" ||\n c === \".\"\n )\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n static shouldAcceptAttribute(attribute: string) {\n if (!DOMSanitizer.IsValidAttributeName(attribute)) {\n console.warn(\"Invalid attribute name\", attribute);\n return false;\n }\n\n // TODO - this might be overly restrictive - apologies to someone that finds this because you have a non-event attribute filtered by this\n return !attribute.startsWith(\"on\");\n }\n}\n", "import {\n AttributeChangedDiff,\n ChildrenChangedDiff,\n ClientMessage,\n NodeDescription,\n RemoteEvent,\n ServerMessage,\n TextChangedDiff,\n} from \"@mml-io/networked-dom-protocol\";\n\nimport { DOMSanitizer } from \"./DOMSanitizer\";\n\nconst websocketProtocol = \"networked-dom-v0.1\";\n\nconst startingBackoffTimeMilliseconds = 100;\nconst maximumBackoffTimeMilliseconds = 10000;\nconst maximumWebsocketConnectionTimeout = 5000;\n\nexport type NetworkedDOMWebsocketFactory = (url: string) => WebSocket;\n\nexport enum NetworkedDOMWebsocketStatus {\n Connecting,\n Connected,\n Reconnecting,\n Disconnected,\n}\n\nfunction isHTMLElement(node: unknown): node is HTMLElement {\n if (node instanceof HTMLElement) {\n return true;\n }\n if (!this.parentElement.ownerDocument.defaultView) {\n return false;\n }\n return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;\n}\n\nfunction isText(node: unknown): node is Text {\n if (node instanceof Text) {\n return true;\n }\n if (!this.parentElement.ownerDocument.defaultView) {\n return false;\n }\n return node instanceof this.parentElement.ownerDocument.defaultView.Text;\n}\n\nexport class NetworkedDOMWebsocket {\n private idToElement = new Map<number, Node>();\n private elementToId = new Map<Node, number>();\n private websocket: WebSocket | null = null;\n private currentRoot: HTMLElement | null = null;\n\n private url: string;\n private websocketFactory: NetworkedDOMWebsocketFactory;\n private parentElement: HTMLElement;\n private timeCallback: (time: number) => void;\n private statusUpdateCallback: (status: NetworkedDOMWebsocketStatus) => void;\n private stopped = false;\n private backoffTime = startingBackoffTimeMilliseconds;\n private status: NetworkedDOMWebsocketStatus | null = null;\n\n public static createWebSocket(url: string): WebSocket {\n return new WebSocket(url, [websocketProtocol]);\n }\n\n constructor(\n url: string,\n websocketFactory: NetworkedDOMWebsocketFactory,\n parentElement: HTMLElement,\n timeCallback?: (time: number) => void,\n statusUpdateCallback?: (status: NetworkedDOMWebsocketStatus) => void,\n ) {\n this.url = url;\n this.websocketFactory = websocketFactory;\n this.parentElement = parentElement;\n this.timeCallback =\n timeCallback ||\n (() => {\n // no-op\n });\n this.statusUpdateCallback =\n statusUpdateCallback ||\n (() => {\n // no-op\n });\n this.setStatus(NetworkedDOMWebsocketStatus.Connecting);\n this.startWebSocketConnectionAttempt();\n }\n\n private setStatus(status: NetworkedDOMWebsocketStatus) {\n if (this.status !== status) {\n this.status = status;\n this.statusUpdateCallback(status);\n }\n }\n\n private createWebsocketWithTimeout(timeout: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"websocket connection timed out\"));\n }, timeout);\n const websocket = this.websocketFactory(this.url);\n websocket.addEventListener(\"open\", () => {\n clearTimeout(timeoutId);\n\n this.websocket = websocket;\n\n websocket.addEventListener(\"message\", (event) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket message event because it is no longer current\");\n websocket.close();\n return;\n }\n this.handleIncomingWebsocketMessage(event);\n });\n\n const onWebsocketClose = async () => {\n const hadContents = this.currentRoot !== null;\n this.clearContents();\n if (this.stopped) {\n // This closing is expected. The client closed the websocket.\n this.setStatus(NetworkedDOMWebsocketStatus.Disconnected);\n return;\n }\n if (!hadContents) {\n // The websocket did not deliver any contents. It may have been successfully opened, but immediately closed. This client should back off to prevent this happening in a rapid loop.\n await this.waitBackoffTime();\n }\n // The websocket closed unexpectedly. Try to reconnect.\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n this.startWebSocketConnectionAttempt();\n };\n\n websocket.addEventListener(\"close\", (e) => {\n if (websocket !== this.websocket) {\n console.warn(\"Ignoring websocket close event because it is no longer current\");\n return;\n }\n console.log(\"NetworkedDOMWebsocket close\", e);\n onWebsocketClose();\n });\n websocket.addEventListener(\"error\", (e) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket error event because it is no longer current\");\n return;\n }\n console.error(\"NetworkedDOMWebsocket error\", e);\n onWebsocketClose();\n });\n\n resolve(websocket);\n });\n websocket.addEventListener(\"error\", (e) => {\n clearTimeout(timeoutId);\n reject(e);\n });\n });\n }\n\n private async waitBackoffTime(): Promise<void> {\n console.warn(`Websocket connection to '${this.url}' failed: retrying in ${this.backoffTime}ms`);\n await new Promise((resolve) => setTimeout(resolve, this.backoffTime));\n this.backoffTime = Math.min(\n // Introduce a small amount of randomness to prevent clients from retrying in lockstep\n this.backoffTime * (1.5 + Math.random() * 0.5),\n maximumBackoffTimeMilliseconds,\n );\n }\n\n private async startWebSocketConnectionAttempt() {\n if (this.stopped) {\n return;\n }\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (this.stopped) {\n return;\n }\n try {\n await this.createWebsocketWithTimeout(maximumWebsocketConnectionTimeout);\n break;\n } catch (e) {\n // Connection failed, retry with backoff\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n await this.waitBackoffTime();\n }\n }\n }\n\n private handleIncomingWebsocketMessage(event: MessageEvent) {\n const messages = JSON.parse(event.data) as Array<ServerMessage>;\n for (const message of messages) {\n if (message.type === \"error\") {\n console.error(\"Error from server\", message);\n } else if (message.type === \"warning\") {\n console.warn(\"Warning from server\", message);\n } else {\n if (message.documentTime) {\n if (this.timeCallback) {\n this.timeCallback(message.documentTime);\n }\n }\n if (message.type === \"snapshot\") {\n // This websocket is successfully connected. Reset the backoff time.\n this.backoffTime = startingBackoffTimeMilliseconds;\n this.setStatus(NetworkedDOMWebsocketStatus.Connected);\n\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n this.elementToId.clear();\n this.idToElement.clear();\n }\n\n // create a tree of DOM elements\n // NOTE: the MLElement contructors are not executed during this stage\n const element = this.handleNewElement(message.snapshot);\n if (!element) {\n throw new Error(\"Snapshot element not created\");\n }\n if (!isHTMLElement(element)) {\n throw new Error(\"Snapshot element is not an HTMLElement\");\n }\n this.currentRoot = element;\n // appending to the tree causes MElements to be constructed\n this.parentElement.append(element);\n } else if (message.type === \"attributeChange\") {\n this.handleAttributeChange(message);\n } else if (message.type === \"childrenChanged\") {\n this.handleChildrenChanged(message);\n } else if (message.type === \"textChanged\") {\n this.handleTextChanged(message);\n } else if (message.type === \"ping\") {\n this.send({\n type: \"pong\",\n pong: message.ping,\n });\n } else {\n console.warn(\"unknown message type\", message);\n }\n }\n }\n }\n\n public stop() {\n this.stopped = true;\n if (this.websocket !== null) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n public handleEvent(element: HTMLElement, event: CustomEvent<{ element: HTMLElement }>) {\n const nodeId = this.elementToId.get(element);\n if (nodeId === undefined || nodeId === null) {\n throw new Error(\"Element not found\");\n }\n\n console.log(\n `Sending event to websocket: \"${event.type}\" on node: ${nodeId} type: ${element.tagName}`,\n );\n\n const detailWithoutElement: Partial<typeof event.detail> = {\n ...event.detail,\n };\n delete detailWithoutElement.element;\n\n const remoteEvent: RemoteEvent = {\n type: \"event\",\n nodeId,\n name: event.type,\n bubbles: event.bubbles,\n params: detailWithoutElement,\n };\n\n this.send(remoteEvent);\n }\n\n private send(fromClientMessage: ClientMessage) {\n if (!this.websocket) {\n throw new Error(\"No websocket created\");\n }\n this.websocket.send(JSON.stringify(fromClientMessage));\n }\n\n private handleTextChanged(message: TextChangedDiff) {\n const { nodeId, text } = message;\n\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in textChanged message\");\n return;\n }\n const node = this.idToElement.get(nodeId);\n if (!node) {\n throw new Error(\"No node found for textChanged message\");\n }\n if (!isText(node)) {\n throw new Error(\"Node for textChanged message is not a Text node\");\n }\n node.textContent = text;\n }\n\n private handleChildrenChanged(message: ChildrenChangedDiff) {\n const { nodeId, addedNodes, removedNodes, previousNodeId } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in childrenChanged message\");\n return;\n }\n const parent = this.idToElement.get(nodeId);\n if (!parent) {\n throw new Error(\"No parent found for childrenChanged message\");\n }\n if (!parent.isConnected) {\n console.error(\"Parent is not connected\", parent);\n }\n if (!isHTMLElement(parent)) {\n throw new Error(\"Parent is not an HTMLElement (that supports children)\");\n }\n let previousElement;\n if (previousNodeId) {\n previousElement = this.idToElement.get(previousNodeId);\n if (!previousElement) {\n throw new Error(\"No previous element found for childrenChanged message\");\n }\n }\n\n for (const addedNode of addedNodes) {\n const childElement = this.handleNewElement(addedNode);\n if (childElement) {\n if (previousElement) {\n const nextElement = previousElement.nextSibling;\n if (nextElement) {\n parent.insertBefore(childElement, nextElement);\n } else {\n parent.append(childElement);\n }\n } else {\n parent.append(childElement);\n }\n }\n }\n for (const removedNode of removedNodes) {\n const childElement = this.idToElement.get(removedNode);\n if (!childElement) {\n throw new Error(`Child element not found: ${removedNode}`);\n }\n this.elementToId.delete(childElement);\n this.idToElement.delete(removedNode);\n parent.removeChild(childElement);\n if (isHTMLElement(childElement)) {\n // If child is capable of supporting children then remove any that exist\n this.removeChildElementIds(childElement);\n }\n }\n }\n\n private removeChildElementIds(parent: HTMLElement) {\n for (let i = 0; i < parent.children.length; i++) {\n const child = parent.children[i];\n const childId = this.elementToId.get(child as HTMLElement);\n if (!childId) {\n console.error(\"Inner child of removed element had no id\", child);\n } else {\n this.elementToId.delete(child);\n this.idToElement.delete(childId);\n }\n this.removeChildElementIds(child as HTMLElement);\n }\n }\n\n private handleAttributeChange(message: AttributeChangedDiff) {\n const { nodeId, attribute, newValue } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in attributeChange message\");\n return;\n }\n const element = this.idToElement.get(nodeId);\n if (element) {\n if (isHTMLElement(element)) {\n if (newValue === null) {\n element.removeAttribute(attribute);\n } else {\n if (DOMSanitizer.shouldAcceptAttribute(attribute)) {\n element.setAttribute(attribute, newValue);\n }\n }\n } else {\n console.error(\"Element is not an HTMLElement and cannot support attributes\", element);\n }\n } else {\n console.error(\"No element found for attributeChange message\");\n }\n }\n\n private handleNewElement(message: NodeDescription): Node | null {\n if (message.type === \"text\") {\n const { nodeId, text } = message;\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n const { tag, nodeId, attributes, children, text } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in handleNewElement message\", message);\n return null;\n }\n if (this.idToElement.has(nodeId)) {\n console.error(\n \"Received nodeId to add that is already present\",\n nodeId,\n this.idToElement.get(nodeId),\n );\n }\n if (tag === \"#text\") {\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text || null;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n\n let element;\n try {\n element = document.createElement(tag);\n } catch (e) {\n console.error(`Error creating element: (${tag})`, e);\n element = document.createElement(\"div\");\n }\n this.idToElement.set(nodeId, element);\n this.elementToId.set(element, nodeId);\n for (const key in attributes) {\n if (DOMSanitizer.shouldAcceptAttribute(key)) {\n const value = attributes[key];\n element.setAttribute(key, value);\n }\n }\n if (children) {\n for (const child of children) {\n const childElement = this.handleNewElement(child);\n if (childElement) {\n element.append(childElement);\n }\n }\n }\n return element;\n }\n\n private clearContents() {\n this.idToElement.clear();\n this.elementToId.clear();\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,eAAN,MAAmB;AAAA,EACxB,OAAO,SAAS,MAAmB;AACjC,QAAI,KAAK,mBAAmB;AAC1B,iBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,YAAI,CAAC,aAAa,qBAAqB,IAAI,GAAG;AAC5C,eAAK,gBAAgB,IAAI;AAAA,QAC3B;AAAA,MACF;AAAA,IACF;AACA,QAAI,KAAK,aAAa,UAAU;AAE9B,WAAK,YAAY;AAAA,IACnB,OAAO;AACL,UAAI,KAAK,mBAAmB;AAC1B,mBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,cAAI,CAAC,aAAa,sBAAsB,IAAI,GAAG;AAC7C,iBAAK,gBAAgB,IAAI;AAAA,UAC3B;AAAA,QACF;AAAA,MACF;AACA,eAAS,IAAI,GAAG,IAAI,KAAK,WAAW,QAAQ,KAAK;AAC/C,qBAAa,SAAS,KAAK,WAAW,CAAC,CAAgB;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAAO,aAAa,GAAoB;AACtC,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA,EAEA,OAAO,aAAa,GAAW;AAC7B,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA,EAEA,OAAO,qBAAqB,YAA6B;AACvD,UAAM,IAAI,WAAW,CAAC;AACtB,QAAI,EAAE,aAAa,aAAa,CAAC,KAAK,MAAM,OAAO,MAAM,MAAM;AAC7D,aAAO;AAAA,IACT;AAEA,aAAS,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;AAC1C,YAAMA,KAAI,WAAW,CAAC;AACtB,UACE,EACE,aAAa,aAAaA,EAAC,KAC3B,aAAa,aAAaA,EAAC,KAC3BA,OAAM,OACNA,OAAM,OACNA,OAAM,OACNA,OAAM,MAER;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,OAAO,sBAAsB,WAAmB;AAC9C,QAAI,CAAC,aAAa,qBAAqB,SAAS,GAAG;AACjD,cAAQ,KAAK,0BAA0B,SAAS;AAChD,aAAO;AAAA,IACT;AAGA,WAAO,CAAC,UAAU,WAAW,IAAI;AAAA,EACnC;AACF;;;
|
|
4
|
+
"sourcesContent": ["export * from \"./NetworkedDOMWebsocket\";\nexport * from \"./DOMSanitizer\";\n", "export class DOMSanitizer {\n static sanitise(node: HTMLElement) {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.IsValidAttributeName(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n if (node.nodeName === \"SCRIPT\") {\n // set text to empty string\n node.innerText = \"\";\n } else {\n if (node.getAttributeNames) {\n for (const attr of node.getAttributeNames()) {\n if (!DOMSanitizer.shouldAcceptAttribute(attr)) {\n node.removeAttribute(attr);\n }\n }\n }\n for (let i = 0; i < node.childNodes.length; i++) {\n DOMSanitizer.sanitise(node.childNodes[i] as HTMLElement);\n }\n }\n }\n\n static IsASCIIDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n }\n\n static IsASCIIAlpha(c: string) {\n return c >= \"a\" && c <= \"z\";\n }\n\n static IsValidAttributeName(characters: string): boolean {\n const c = characters[0];\n if (!(DOMSanitizer.IsASCIIAlpha(c) || c === \":\" || c === \"_\")) {\n return false;\n }\n\n for (let i = 1; i < characters.length; i++) {\n const c = characters[i];\n if (\n !(\n DOMSanitizer.IsASCIIDigit(c) ||\n DOMSanitizer.IsASCIIAlpha(c) ||\n c === \":\" ||\n c === \"_\" ||\n c === \"-\" ||\n c === \".\"\n )\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n static shouldAcceptAttribute(attribute: string) {\n if (!DOMSanitizer.IsValidAttributeName(attribute)) {\n console.warn(\"Invalid attribute name\", attribute);\n return false;\n }\n\n // TODO - this might be overly restrictive - apologies to someone that finds this because you have a non-event attribute filtered by this\n return !attribute.startsWith(\"on\");\n }\n}\n", "import {\n AttributeChangedDiff,\n ChildrenChangedDiff,\n ClientMessage,\n NodeDescription,\n RemoteEvent,\n ServerMessage,\n SnapshotMessage,\n TextChangedDiff,\n} from \"@mml-io/networked-dom-protocol\";\n\nimport { DOMSanitizer } from \"./DOMSanitizer\";\n\nconst websocketProtocol = \"networked-dom-v0.1\";\n\nconst startingBackoffTimeMilliseconds = 100;\nconst maximumBackoffTimeMilliseconds = 10000;\nconst maximumWebsocketConnectionTimeout = 5000;\n\nexport type NetworkedDOMWebsocketFactory = (url: string) => WebSocket;\n\nexport enum NetworkedDOMWebsocketStatus {\n Connecting,\n Connected,\n Reconnecting,\n Disconnected,\n}\n\nexport class NetworkedDOMWebsocket {\n private idToElement = new Map<number, Node>();\n private elementToId = new Map<Node, number>();\n private websocket: WebSocket | null = null;\n private currentRoot: HTMLElement | null = null;\n\n private url: string;\n private websocketFactory: NetworkedDOMWebsocketFactory;\n private parentElement: HTMLElement;\n private timeCallback: (time: number) => void;\n private statusUpdateCallback: (status: NetworkedDOMWebsocketStatus) => void;\n private stopped = false;\n private backoffTime = startingBackoffTimeMilliseconds;\n private status: NetworkedDOMWebsocketStatus | null = null;\n\n public static createWebSocket(url: string): WebSocket {\n return new WebSocket(url, [websocketProtocol]);\n }\n\n constructor(\n url: string,\n websocketFactory: NetworkedDOMWebsocketFactory,\n parentElement: HTMLElement,\n timeCallback?: (time: number) => void,\n statusUpdateCallback?: (status: NetworkedDOMWebsocketStatus) => void,\n ) {\n this.url = url;\n this.websocketFactory = websocketFactory;\n this.parentElement = parentElement;\n this.timeCallback =\n timeCallback ||\n (() => {\n // no-op\n });\n this.statusUpdateCallback =\n statusUpdateCallback ||\n (() => {\n // no-op\n });\n this.setStatus(NetworkedDOMWebsocketStatus.Connecting);\n this.startWebSocketConnectionAttempt();\n }\n\n private setStatus(status: NetworkedDOMWebsocketStatus) {\n if (this.status !== status) {\n this.status = status;\n this.statusUpdateCallback(status);\n }\n }\n\n private isHTMLElement(node: unknown): node is HTMLElement {\n if (node instanceof HTMLElement) {\n return true;\n }\n if (!this.parentElement.ownerDocument.defaultView) {\n return false;\n }\n return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;\n }\n\n private isText(node: unknown): node is Text {\n if (node instanceof Text) {\n return true;\n }\n if (!this.parentElement.ownerDocument.defaultView) {\n return false;\n }\n return node instanceof this.parentElement.ownerDocument.defaultView.Text;\n }\n\n private createWebsocketWithTimeout(timeout: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"websocket connection timed out\"));\n }, timeout);\n const websocket = this.websocketFactory(this.url);\n websocket.addEventListener(\"open\", () => {\n clearTimeout(timeoutId);\n\n this.websocket = websocket;\n\n websocket.addEventListener(\"message\", (event) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket message event because it is no longer current\");\n websocket.close();\n return;\n }\n this.handleIncomingWebsocketMessage(event);\n });\n\n const onWebsocketClose = async () => {\n const hadContents = this.currentRoot !== null;\n this.clearContents();\n if (this.stopped) {\n // This closing is expected. The client closed the websocket.\n this.setStatus(NetworkedDOMWebsocketStatus.Disconnected);\n return;\n }\n if (!hadContents) {\n // The websocket did not deliver any contents. It may have been successfully opened, but immediately closed. This client should back off to prevent this happening in a rapid loop.\n await this.waitBackoffTime();\n }\n // The websocket closed unexpectedly. Try to reconnect.\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n this.startWebSocketConnectionAttempt();\n };\n\n websocket.addEventListener(\"close\", (e) => {\n if (websocket !== this.websocket) {\n console.warn(\"Ignoring websocket close event because it is no longer current\");\n return;\n }\n console.log(\"NetworkedDOMWebsocket close\", e);\n onWebsocketClose();\n });\n websocket.addEventListener(\"error\", (e) => {\n if (websocket !== this.websocket) {\n console.log(\"Ignoring websocket error event because it is no longer current\");\n return;\n }\n console.error(\"NetworkedDOMWebsocket error\", e);\n onWebsocketClose();\n });\n\n resolve(websocket);\n });\n websocket.addEventListener(\"error\", (e) => {\n clearTimeout(timeoutId);\n reject(e);\n });\n });\n }\n\n private async waitBackoffTime(): Promise<void> {\n console.warn(`Websocket connection to '${this.url}' failed: retrying in ${this.backoffTime}ms`);\n await new Promise((resolve) => setTimeout(resolve, this.backoffTime));\n this.backoffTime = Math.min(\n // Introduce a small amount of randomness to prevent clients from retrying in lockstep\n this.backoffTime * (1.5 + Math.random() * 0.5),\n maximumBackoffTimeMilliseconds,\n );\n }\n\n private async startWebSocketConnectionAttempt() {\n if (this.stopped) {\n return;\n }\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (this.stopped) {\n return;\n }\n try {\n await this.createWebsocketWithTimeout(maximumWebsocketConnectionTimeout);\n break;\n } catch (e) {\n // Connection failed, retry with backoff\n this.setStatus(NetworkedDOMWebsocketStatus.Reconnecting);\n await this.waitBackoffTime();\n }\n }\n }\n\n private handleIncomingWebsocketMessage(event: MessageEvent) {\n const messages = JSON.parse(event.data) as Array<ServerMessage>;\n for (const message of messages) {\n switch (message.type) {\n case \"error\":\n console.error(\"Error from server\", message);\n break;\n case \"warning\":\n console.warn(\"Warning from server\", message);\n break;\n default: {\n if (message.documentTime) {\n if (this.timeCallback) {\n this.timeCallback(message.documentTime);\n }\n }\n switch (message.type) {\n case \"snapshot\":\n this.handleSnapshot(message);\n break;\n case \"attributeChange\":\n this.handleAttributeChange(message);\n break;\n case \"childrenChanged\":\n this.handleChildrenChanged(message);\n break;\n case \"textChanged\":\n this.handleTextChanged(message);\n break;\n case \"ping\":\n this.send({\n type: \"pong\",\n pong: message.ping,\n });\n break;\n default:\n console.warn(\"unknown message type\", message);\n break;\n }\n }\n }\n }\n }\n\n public stop() {\n this.stopped = true;\n if (this.websocket !== null) {\n this.websocket.close();\n this.websocket = null;\n }\n }\n\n public handleEvent(element: HTMLElement, event: CustomEvent<{ element: HTMLElement }>) {\n const nodeId = this.elementToId.get(element);\n if (nodeId === undefined || nodeId === null) {\n throw new Error(\"Element not found\");\n }\n\n console.log(\n `Sending event to websocket: \"${event.type}\" on node: ${nodeId} type: ${element.tagName}`,\n );\n\n const detailWithoutElement: Partial<typeof event.detail> = {\n ...event.detail,\n };\n delete detailWithoutElement.element;\n\n const remoteEvent: RemoteEvent = {\n type: \"event\",\n nodeId,\n name: event.type,\n bubbles: event.bubbles,\n params: detailWithoutElement,\n };\n\n this.send(remoteEvent);\n }\n\n private send(fromClientMessage: ClientMessage) {\n if (!this.websocket) {\n throw new Error(\"No websocket created\");\n }\n this.websocket.send(JSON.stringify(fromClientMessage));\n }\n\n private handleTextChanged(message: TextChangedDiff) {\n const { nodeId, text } = message;\n\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in textChanged message\");\n return;\n }\n const node = this.idToElement.get(nodeId);\n if (!node) {\n throw new Error(\"No node found for textChanged message\");\n }\n if (!this.isText(node)) {\n throw new Error(\"Node for textChanged message is not a Text node\");\n }\n node.textContent = text;\n }\n\n private handleChildrenChanged(message: ChildrenChangedDiff) {\n const { nodeId, addedNodes, removedNodes, previousNodeId } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in childrenChanged message\");\n return;\n }\n const parent = this.idToElement.get(nodeId);\n if (!parent) {\n throw new Error(\"No parent found for childrenChanged message\");\n }\n if (!parent.isConnected) {\n console.error(\"Parent is not connected\", parent);\n }\n if (!this.isHTMLElement(parent)) {\n throw new Error(\"Parent is not an HTMLElement (that supports children)\");\n }\n let previousElement;\n if (previousNodeId) {\n previousElement = this.idToElement.get(previousNodeId);\n if (!previousElement) {\n throw new Error(\"No previous element found for childrenChanged message\");\n }\n }\n\n for (const addedNode of addedNodes) {\n const childElement = this.handleNewElement(addedNode);\n if (childElement) {\n if (previousElement) {\n const nextElement = previousElement.nextSibling;\n if (nextElement) {\n parent.insertBefore(childElement, nextElement);\n } else {\n parent.append(childElement);\n }\n } else {\n parent.append(childElement);\n }\n }\n }\n for (const removedNode of removedNodes) {\n const childElement = this.idToElement.get(removedNode);\n if (!childElement) {\n throw new Error(`Child element not found: ${removedNode}`);\n }\n this.elementToId.delete(childElement);\n this.idToElement.delete(removedNode);\n parent.removeChild(childElement);\n if (this.isHTMLElement(childElement)) {\n // If child is capable of supporting children then remove any that exist\n this.removeChildElementIds(childElement);\n }\n }\n }\n\n private removeChildElementIds(parent: HTMLElement) {\n for (let i = 0; i < parent.children.length; i++) {\n const child = parent.children[i];\n const childId = this.elementToId.get(child as HTMLElement);\n if (!childId) {\n console.error(\"Inner child of removed element had no id\", child);\n } else {\n this.elementToId.delete(child);\n this.idToElement.delete(childId);\n }\n this.removeChildElementIds(child as HTMLElement);\n }\n }\n\n private handleSnapshot(message: SnapshotMessage) {\n // This websocket is successfully connected. Reset the backoff time.\n this.backoffTime = startingBackoffTimeMilliseconds;\n this.setStatus(NetworkedDOMWebsocketStatus.Connected);\n\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n this.elementToId.clear();\n this.idToElement.clear();\n }\n\n // create a tree of DOM elements\n // NOTE: the MElement constructors are not executed during this stage\n const element = this.handleNewElement(message.snapshot);\n if (!element) {\n throw new Error(\"Snapshot element not created\");\n }\n if (!this.isHTMLElement(element)) {\n throw new Error(\"Snapshot element is not an HTMLElement\");\n }\n this.currentRoot = element;\n // appending to the tree causes MElements to be constructed\n this.parentElement.append(element);\n }\n\n private handleAttributeChange(message: AttributeChangedDiff) {\n const { nodeId, attribute, newValue } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in attributeChange message\");\n return;\n }\n const element = this.idToElement.get(nodeId);\n if (element) {\n if (this.isHTMLElement(element)) {\n if (newValue === null) {\n element.removeAttribute(attribute);\n } else {\n if (DOMSanitizer.shouldAcceptAttribute(attribute)) {\n element.setAttribute(attribute, newValue);\n }\n }\n } else {\n console.error(\"Element is not an HTMLElement and cannot support attributes\", element);\n }\n } else {\n console.error(\"No element found for attributeChange message\");\n }\n }\n\n private handleNewElement(message: NodeDescription): Node | null {\n if (message.type === \"text\") {\n const { nodeId, text } = message;\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n const { tag, nodeId, attributes, children, text } = message;\n if (nodeId === undefined || nodeId === null) {\n console.warn(\"No nodeId in handleNewElement message\", message);\n return null;\n }\n if (this.idToElement.has(nodeId)) {\n console.error(\n \"Received nodeId to add that is already present\",\n nodeId,\n this.idToElement.get(nodeId),\n );\n }\n if (tag === \"#text\") {\n const textNode = document.createTextNode(\"\");\n textNode.textContent = text || null;\n this.idToElement.set(nodeId, textNode);\n this.elementToId.set(textNode, nodeId);\n return textNode;\n }\n\n let element;\n try {\n element = document.createElement(tag);\n } catch (e) {\n console.error(`Error creating element: (${tag})`, e);\n element = document.createElement(\"div\");\n }\n this.idToElement.set(nodeId, element);\n this.elementToId.set(element, nodeId);\n for (const key in attributes) {\n if (DOMSanitizer.shouldAcceptAttribute(key)) {\n const value = attributes[key];\n element.setAttribute(key, value);\n }\n }\n if (children) {\n for (const child of children) {\n const childElement = this.handleNewElement(child);\n if (childElement) {\n element.append(childElement);\n }\n }\n }\n return element;\n }\n\n private clearContents() {\n this.idToElement.clear();\n this.elementToId.clear();\n if (this.currentRoot) {\n this.currentRoot.remove();\n this.currentRoot = null;\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,eAAN,MAAmB;AAAA,EACxB,OAAO,SAAS,MAAmB;AACjC,QAAI,KAAK,mBAAmB;AAC1B,iBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,YAAI,CAAC,aAAa,qBAAqB,IAAI,GAAG;AAC5C,eAAK,gBAAgB,IAAI;AAAA,QAC3B;AAAA,MACF;AAAA,IACF;AACA,QAAI,KAAK,aAAa,UAAU;AAE9B,WAAK,YAAY;AAAA,IACnB,OAAO;AACL,UAAI,KAAK,mBAAmB;AAC1B,mBAAW,QAAQ,KAAK,kBAAkB,GAAG;AAC3C,cAAI,CAAC,aAAa,sBAAsB,IAAI,GAAG;AAC7C,iBAAK,gBAAgB,IAAI;AAAA,UAC3B;AAAA,QACF;AAAA,MACF;AACA,eAAS,IAAI,GAAG,IAAI,KAAK,WAAW,QAAQ,KAAK;AAC/C,qBAAa,SAAS,KAAK,WAAW,CAAC,CAAgB;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAAO,aAAa,GAAoB;AACtC,WA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]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mml-io/networked-dom-web",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"main": "./build/index.js",
|
|
5
5
|
"types": "./build/index.d.ts",
|
|
6
6
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"test-iterate": "jest --watch"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@mml-io/networked-dom-protocol": "^0.
|
|
21
|
+
"@mml-io/networked-dom-protocol": "^0.2.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"jest-canvas-mock": "2.5.1",
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
NodeDescription,
|
|
6
6
|
RemoteEvent,
|
|
7
7
|
ServerMessage,
|
|
8
|
+
SnapshotMessage,
|
|
8
9
|
TextChangedDiff,
|
|
9
10
|
} from "@mml-io/networked-dom-protocol";
|
|
10
11
|
|
|
@@ -25,26 +26,6 @@ export enum NetworkedDOMWebsocketStatus {
|
|
|
25
26
|
Disconnected,
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
function isHTMLElement(node: unknown): node is HTMLElement {
|
|
29
|
-
if (node instanceof HTMLElement) {
|
|
30
|
-
return true;
|
|
31
|
-
}
|
|
32
|
-
if (!this.parentElement.ownerDocument.defaultView) {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function isText(node: unknown): node is Text {
|
|
39
|
-
if (node instanceof Text) {
|
|
40
|
-
return true;
|
|
41
|
-
}
|
|
42
|
-
if (!this.parentElement.ownerDocument.defaultView) {
|
|
43
|
-
return false;
|
|
44
|
-
}
|
|
45
|
-
return node instanceof this.parentElement.ownerDocument.defaultView.Text;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
29
|
export class NetworkedDOMWebsocket {
|
|
49
30
|
private idToElement = new Map<number, Node>();
|
|
50
31
|
private elementToId = new Map<Node, number>();
|
|
@@ -95,6 +76,26 @@ export class NetworkedDOMWebsocket {
|
|
|
95
76
|
}
|
|
96
77
|
}
|
|
97
78
|
|
|
79
|
+
private isHTMLElement(node: unknown): node is HTMLElement {
|
|
80
|
+
if (node instanceof HTMLElement) {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
if (!this.parentElement.ownerDocument.defaultView) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return node instanceof this.parentElement.ownerDocument.defaultView.HTMLElement;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private isText(node: unknown): node is Text {
|
|
90
|
+
if (node instanceof Text) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
if (!this.parentElement.ownerDocument.defaultView) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
return node instanceof this.parentElement.ownerDocument.defaultView.Text;
|
|
97
|
+
}
|
|
98
|
+
|
|
98
99
|
private createWebsocketWithTimeout(timeout: number): Promise<WebSocket> {
|
|
99
100
|
return new Promise((resolve, reject) => {
|
|
100
101
|
const timeoutId = setTimeout(() => {
|
|
@@ -191,53 +192,42 @@ export class NetworkedDOMWebsocket {
|
|
|
191
192
|
private handleIncomingWebsocketMessage(event: MessageEvent) {
|
|
192
193
|
const messages = JSON.parse(event.data) as Array<ServerMessage>;
|
|
193
194
|
for (const message of messages) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
this.backoffTime = startingBackoffTimeMilliseconds;
|
|
207
|
-
this.setStatus(NetworkedDOMWebsocketStatus.Connected);
|
|
208
|
-
|
|
209
|
-
if (this.currentRoot) {
|
|
210
|
-
this.currentRoot.remove();
|
|
211
|
-
this.currentRoot = null;
|
|
212
|
-
this.elementToId.clear();
|
|
213
|
-
this.idToElement.clear();
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// create a tree of DOM elements
|
|
217
|
-
// NOTE: the MLElement contructors are not executed during this stage
|
|
218
|
-
const element = this.handleNewElement(message.snapshot);
|
|
219
|
-
if (!element) {
|
|
220
|
-
throw new Error("Snapshot element not created");
|
|
195
|
+
switch (message.type) {
|
|
196
|
+
case "error":
|
|
197
|
+
console.error("Error from server", message);
|
|
198
|
+
break;
|
|
199
|
+
case "warning":
|
|
200
|
+
console.warn("Warning from server", message);
|
|
201
|
+
break;
|
|
202
|
+
default: {
|
|
203
|
+
if (message.documentTime) {
|
|
204
|
+
if (this.timeCallback) {
|
|
205
|
+
this.timeCallback(message.documentTime);
|
|
206
|
+
}
|
|
221
207
|
}
|
|
222
|
-
|
|
223
|
-
|
|
208
|
+
switch (message.type) {
|
|
209
|
+
case "snapshot":
|
|
210
|
+
this.handleSnapshot(message);
|
|
211
|
+
break;
|
|
212
|
+
case "attributeChange":
|
|
213
|
+
this.handleAttributeChange(message);
|
|
214
|
+
break;
|
|
215
|
+
case "childrenChanged":
|
|
216
|
+
this.handleChildrenChanged(message);
|
|
217
|
+
break;
|
|
218
|
+
case "textChanged":
|
|
219
|
+
this.handleTextChanged(message);
|
|
220
|
+
break;
|
|
221
|
+
case "ping":
|
|
222
|
+
this.send({
|
|
223
|
+
type: "pong",
|
|
224
|
+
pong: message.ping,
|
|
225
|
+
});
|
|
226
|
+
break;
|
|
227
|
+
default:
|
|
228
|
+
console.warn("unknown message type", message);
|
|
229
|
+
break;
|
|
224
230
|
}
|
|
225
|
-
this.currentRoot = element;
|
|
226
|
-
// appending to the tree causes MElements to be constructed
|
|
227
|
-
this.parentElement.append(element);
|
|
228
|
-
} else if (message.type === "attributeChange") {
|
|
229
|
-
this.handleAttributeChange(message);
|
|
230
|
-
} else if (message.type === "childrenChanged") {
|
|
231
|
-
this.handleChildrenChanged(message);
|
|
232
|
-
} else if (message.type === "textChanged") {
|
|
233
|
-
this.handleTextChanged(message);
|
|
234
|
-
} else if (message.type === "ping") {
|
|
235
|
-
this.send({
|
|
236
|
-
type: "pong",
|
|
237
|
-
pong: message.ping,
|
|
238
|
-
});
|
|
239
|
-
} else {
|
|
240
|
-
console.warn("unknown message type", message);
|
|
241
231
|
}
|
|
242
232
|
}
|
|
243
233
|
}
|
|
@@ -295,7 +285,7 @@ export class NetworkedDOMWebsocket {
|
|
|
295
285
|
if (!node) {
|
|
296
286
|
throw new Error("No node found for textChanged message");
|
|
297
287
|
}
|
|
298
|
-
if (!isText(node)) {
|
|
288
|
+
if (!this.isText(node)) {
|
|
299
289
|
throw new Error("Node for textChanged message is not a Text node");
|
|
300
290
|
}
|
|
301
291
|
node.textContent = text;
|
|
@@ -314,7 +304,7 @@ export class NetworkedDOMWebsocket {
|
|
|
314
304
|
if (!parent.isConnected) {
|
|
315
305
|
console.error("Parent is not connected", parent);
|
|
316
306
|
}
|
|
317
|
-
if (!isHTMLElement(parent)) {
|
|
307
|
+
if (!this.isHTMLElement(parent)) {
|
|
318
308
|
throw new Error("Parent is not an HTMLElement (that supports children)");
|
|
319
309
|
}
|
|
320
310
|
let previousElement;
|
|
@@ -348,7 +338,7 @@ export class NetworkedDOMWebsocket {
|
|
|
348
338
|
this.elementToId.delete(childElement);
|
|
349
339
|
this.idToElement.delete(removedNode);
|
|
350
340
|
parent.removeChild(childElement);
|
|
351
|
-
if (isHTMLElement(childElement)) {
|
|
341
|
+
if (this.isHTMLElement(childElement)) {
|
|
352
342
|
// If child is capable of supporting children then remove any that exist
|
|
353
343
|
this.removeChildElementIds(childElement);
|
|
354
344
|
}
|
|
@@ -369,6 +359,32 @@ export class NetworkedDOMWebsocket {
|
|
|
369
359
|
}
|
|
370
360
|
}
|
|
371
361
|
|
|
362
|
+
private handleSnapshot(message: SnapshotMessage) {
|
|
363
|
+
// This websocket is successfully connected. Reset the backoff time.
|
|
364
|
+
this.backoffTime = startingBackoffTimeMilliseconds;
|
|
365
|
+
this.setStatus(NetworkedDOMWebsocketStatus.Connected);
|
|
366
|
+
|
|
367
|
+
if (this.currentRoot) {
|
|
368
|
+
this.currentRoot.remove();
|
|
369
|
+
this.currentRoot = null;
|
|
370
|
+
this.elementToId.clear();
|
|
371
|
+
this.idToElement.clear();
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// create a tree of DOM elements
|
|
375
|
+
// NOTE: the MElement constructors are not executed during this stage
|
|
376
|
+
const element = this.handleNewElement(message.snapshot);
|
|
377
|
+
if (!element) {
|
|
378
|
+
throw new Error("Snapshot element not created");
|
|
379
|
+
}
|
|
380
|
+
if (!this.isHTMLElement(element)) {
|
|
381
|
+
throw new Error("Snapshot element is not an HTMLElement");
|
|
382
|
+
}
|
|
383
|
+
this.currentRoot = element;
|
|
384
|
+
// appending to the tree causes MElements to be constructed
|
|
385
|
+
this.parentElement.append(element);
|
|
386
|
+
}
|
|
387
|
+
|
|
372
388
|
private handleAttributeChange(message: AttributeChangedDiff) {
|
|
373
389
|
const { nodeId, attribute, newValue } = message;
|
|
374
390
|
if (nodeId === undefined || nodeId === null) {
|
|
@@ -377,7 +393,7 @@ export class NetworkedDOMWebsocket {
|
|
|
377
393
|
}
|
|
378
394
|
const element = this.idToElement.get(nodeId);
|
|
379
395
|
if (element) {
|
|
380
|
-
if (isHTMLElement(element)) {
|
|
396
|
+
if (this.isHTMLElement(element)) {
|
|
381
397
|
if (newValue === null) {
|
|
382
398
|
element.removeAttribute(attribute);
|
|
383
399
|
} else {
|