forked from Matt-Esch/virtual-dom
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrender.js
executable file
·140 lines (116 loc) · 2.31 KB
/
render.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
var singleTag = {
area: true,
base: true,
basefont: true,
br: true,
col: true,
command: true,
embed: true,
frame: true,
hr: true,
img: true,
input: true,
isindex: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
}
, booleanAttributes = {
allowfullscreen: true,
async: true,
autofocus: true,
autoplay: true,
checked: true,
controls: true,
default: true,
defer: true,
disabled: true,
hidden: true,
ismap: true,
loop: true,
multiple: true,
muted: true,
open: true,
readonly: true,
required: true,
reversed: true,
scoped: true,
seamless: true,
selected: true,
typemustmatch: true
}
, REG_CAP = /[A-Z]/g;
function isEle(node) {
return node.tag !== 'text';
}
function formatStyle(style) {
var key, value
, output = 'style="';
for (key in style) {
value = style[key];
key = key.replace(REG_CAP, function (cap) {
return '-' + cap.toLowerCase();
});
output += key + ': ' + value + ';';
}
return output + '"';
}
function formatProps(props) {
if (!props) return;
var output = ''
, key
, value;
for (key in props) {
value = props[key];
if (output) {
output += ' ';
}
if (!value && booleanAttributes[key]) {
output += key;
} else if (key === 'style') {
output += formatStyle(value);
} else {
output += key + '="' + value + '"';
}
}
return output;
}
function renderTag(vd) {
var tag = '<'+ vd.tag
, props = formatProps(vd.props);
if (props) {
tag += ' ' + props;
}
tag += '>';
if (vd.children) {
tag += render(vd.children);
}
if (!singleTag[vd.tag]) {
tag += '</' + vd.tag + '>';
}
return tag;
}
function renderText(vd) {
return vd.text;
}
function render(vds) {
!Array.isArray(vds) &&
(vds = [vds]);
var output = ''
, l = vds.length
, vd;
for (var i = 0; i < l; i++) {
vd = vds[i]
if (isEle(vd)) {
output += renderTag(vd);
} else {
output += renderText(vd);
}
}
return output;
}
module.exports = render;