-
Notifications
You must be signed in to change notification settings - Fork 170
/
deserialize.ts
executable file
·55 lines (45 loc) · 1.49 KB
/
deserialize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { setLock } from "./constructor-lock.ts";
import { Element } from "./element.ts";
import { Comment, Node, NodeType, Text } from "./node.ts";
import { parse, parseFrag } from "./parser.ts";
export function nodesFromString(html: string): Node {
setLock(false);
const parsed = JSON.parse(parse(html));
const node = nodeFromArray(parsed, null);
setLock(true);
return node;
}
export function fragmentNodesFromString(html: string): Node {
setLock(false);
const parsed = JSON.parse(parseFrag(html));
const node = nodeFromArray(parsed, null);
setLock(true);
return node;
}
function nodeFromArray(data: any, parentNode: Node | null): Node {
// For reference only:
// type node = [NodeType, nodeName, attributes, node[]]
// | [NodeType, characterData]
const elm = new Element(data[1], parentNode, data[2]);
const childNodes = elm._getChildNodesMutator();
let childNode: Node;
for (const child of data.slice(3)) {
switch (child[0]) {
case NodeType.TEXT_NODE:
childNode = new Text(child[1]);
childNode.parentNode = childNode.parentElement = <Element>elm;
childNodes.push(childNode);
break;
case NodeType.COMMENT_NODE:
childNode = new Comment(child[1]);
childNode.parentNode = childNode.parentElement = <Element>elm;
childNodes.push(childNode);
break;
case NodeType.DOCUMENT_NODE:
case NodeType.ELEMENT_NODE:
nodeFromArray(child, elm);
break;
}
}
return elm;
}