-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvnode.ts
46 lines (41 loc) · 1.16 KB
/
vnode.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
export class VNode<T extends keyof HTMLElementTagNameMap> {
constructor(
public tagName: T,
public attrs: Partial<HTMLElementTagNameMap[T]> | null | undefined,
public children: (VNode<any> | string)[]
) {}
render() {
const node = document.createElement(this.tagName)
this.setNodeAttr(node)
if (this.children.length) {
this.children.forEach(child => {
if (child instanceof VNode) {
node.appendChild(child.render())
}
if (typeof child === 'string') {
node.appendChild(document.createTextNode(child))
}
})
}
return node
}
private setNodeAttr(node: HTMLElementTagNameMap[T]) {
for (let key in this.attrs) {
if (!this.attrs.hasOwnProperty(key)) {
return
}
if (key === 'style') {
node.style.cssText = this.attrs[key] as any
} else {
node.setAttribute(key, this.attrs[key] as any)
}
}
}
}
export const createElement = <T extends keyof HTMLElementTagNameMap>(
tagName: VNode<T>['tagName'],
attrs?: VNode<T>['attrs'],
children?: VNode<T>['children']
) => {
return new VNode(tagName, attrs || {}, children || [])
}