UNPKG

1.62 kBPlain TextView Raw
1import { addNS } from "./h";
2import { vnode, VNode } from "./vnode";
3import { htmlDomApi, DOMAPI } from "./htmldomapi";
4
5export function toVNode(node: Node, domApi?: DOMAPI): VNode {
6 const api: DOMAPI = domApi !== undefined ? domApi : htmlDomApi;
7 let text: string;
8 if (api.isElement(node)) {
9 const id = node.id ? "#" + node.id : "";
10 const cn = node.getAttribute("class");
11 const c = cn ? "." + cn.split(" ").join(".") : "";
12 const sel = api.tagName(node).toLowerCase() + id + c;
13 const attrs: any = {};
14 const children: VNode[] = [];
15 let name: string;
16 let i: number, n: number;
17 const elmAttrs = node.attributes;
18 const elmChildren = node.childNodes;
19 for (i = 0, n = elmAttrs.length; i < n; i++) {
20 name = elmAttrs[i].nodeName;
21 if (name !== "id" && name !== "class") {
22 attrs[name] = elmAttrs[i].nodeValue;
23 }
24 }
25 for (i = 0, n = elmChildren.length; i < n; i++) {
26 children.push(toVNode(elmChildren[i], domApi));
27 }
28 const data = { attrs };
29 if (
30 sel[0] === "s" &&
31 sel[1] === "v" &&
32 sel[2] === "g" &&
33 (sel.length === 3 || sel[3] === "." || sel[3] === "#")
34 ) {
35 addNS(data, children, sel);
36 }
37 return vnode(sel, data, children, undefined, node);
38 } else if (api.isText(node)) {
39 text = api.getTextContent(node) as string;
40 return vnode(undefined, undefined, undefined, text, node);
41 } else if (api.isComment(node)) {
42 text = api.getTextContent(node) as string;
43 return vnode("!", {}, [], text, node as any);
44 } else {
45 return vnode("", {}, [], undefined, node as any);
46 }
47}