-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoy-react.js
74 lines (64 loc) · 1.58 KB
/
toy-react.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const ROOT = Symbol('root')
class ElementWrapper {
constructor(type) {
this.root = document.createElement(type)
}
setAttribute(name, value) {
this.root.setAttribute(name, value)
}
appendChild(child) {
this.root.appendChild(child.root)
}
}
class TextWrapper {
constructor(content) {
this.root = document.createTextNode(content)
}
}
export class Component {
constructor() {
this.props = Object.create(null)
this.children = []
this[ROOT] = null
}
setAttribute(name, value) {
this.props[name] = value
}
appendChild(child) {
this.children.push(child)
}
get root() {
if (!this[ROOT]) {
this[ROOT] = this.render().root
}
return this[ROOT]
}
}
export const createElement = (type, attributes, ...children) => {
let e
if (typeof type === 'string') {
e = new ElementWrapper(type)
} else {
e = new type
}
for (const p in attributes) {
e.setAttribute(p, attributes[p])
}
const insertChildren = children => {
for (let child of children) {
if (typeof child === 'string') {
child = new TextWrapper(child)
}
if (typeof child === 'object' && child instanceof Array) {
insertChildren(child)
} else {
e.appendChild(child)
}
}
}
insertChildren(children)
return e
}
export const render = (component, parentComponent) => {
parentComponent.appendChild(component.root)
}