basic rebuild implementation

This commit is contained in:
Yanzhen Yu
2018-09-30 15:26:00 +08:00
parent 819cf3062e
commit 3edd364c3b
4 changed files with 193 additions and 137 deletions

46
src/rebuild.ts Normal file
View File

@@ -0,0 +1,46 @@
import { serializedNodeWithId, NodeType } from './types';
function buildNode(n: serializedNodeWithId): Node | null {
switch (n.type) {
case NodeType.Document:
return document.implementation.createDocument(null, '', null);
case NodeType.DocumentType:
return document.implementation.createDocumentType(
n.name,
n.publicId,
n.systemId,
);
case NodeType.Element:
const node = document.createElement(n.tagName);
for (const name in n.attributes) {
if (n.attributes.hasOwnProperty(name)) {
node.setAttribute(name, n.attributes[name]);
}
}
return node;
case NodeType.Text:
return document.createTextNode(n.textContent);
case NodeType.CDATA:
return document.createCDATASection(n.textContent);
case NodeType.Comment:
return document.createComment(n.textContent);
default:
return null;
}
}
function rebuild(n: serializedNodeWithId): Node | null {
const root = buildNode(n);
if (!root) {
return null;
}
if (n.type === NodeType.Document || n.type === NodeType.Element) {
for (const childN of n.childNodes) {
const childNode = rebuild(childN);
root.appendChild(childNode);
}
}
return root;
}
export default rebuild;