-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
102 lines (91 loc) · 2.38 KB
/
index.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var element = require('virtual-element');
var eventRegex = /^on[A-Z]/;
/**
* Renders a component tree.
*/
function render(node){
switch (nodeType(node)) {
case "text": return document.createTextNode(node);
case "element": return renderElement(node);
case "component": return renderComponent(node);
}
}
module.exports = {
render,
element
};
function nodeType (node) {
var type = valType(node);
if (type !== 'object') {
return 'text';
}
if (valType(node.type) === 'string') {
return 'element';
}
return 'component';
}
function valType (val) {
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val);
return typeof val;
}
function setAttribute(element, name, value) {
switch (name) {
case 'checked':
case 'disabled':
case 'selected':
element[name] = true;
break;
case 'innerHTML':
element.innerHTML = value;
break;
case 'value':
element.value = value;
break;
default:
element.setAttribute(name, value);
break;
}
}
function normalizeComponent({render, defaultProps, name}, attributes, children) {
var props = {
children
};
Object.keys(attributes || {}).forEach(function(attribute){
props[attribute] = attributes[attribute];
});
Object.keys(defaultProps || {}).forEach(function(attribute){
//Do not overwrite existing props with it's default value
if (!props[attribute]) {
props[attribute] = defaultProps[attribute];
}
});
return {
props,
render,
displayName: name || 'Component'
};
}
function renderElement({type, attributes, children}) {
let element = document.createElement(type);
Object.keys(attributes).forEach(function(attributeName){
if (eventRegex.test(attributeName)) {
element.addEventListener(attributeName.substr(2).toLowerCase(), attributes[attributeName]);
} else {
setAttribute(element, attributeName, attributes[attributeName]);
}
});
children.forEach(function(child){
element.appendChild(render(child));
});
return element;
}
function renderComponent({type, attributes, children}) {
var component = normalizeComponent(type, attributes, children);
var fn = component.render;
if (!fn) throw new Error('Component needs a render function');
var node = fn(component.props);
if (!node) throw new Error('Render function must return an element.');
return render(node);
}