-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
101 lines (85 loc) · 2.63 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
var escape = require('escape-html');
var extend = require('xtend');
var isVNode = require('virtual-dom/vnode/is-vnode');
var isVText = require('virtual-dom/vnode/is-vtext');
var isThunk = require('virtual-dom/vnode/is-thunk');
var isWidget = require('virtual-dom/vnode/is-widget');
var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook');
var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook');
var paramCase = require('param-case');
var createAttribute = require('./create-attribute');
var voidElements = require('./void-elements');
module.exports = toHTML;
function toHTML(node, parent) {
if (!node) return '';
if (isThunk(node)) {
node = node.render();
}
if (isWidget(node) && node.render) {
node = node.render();
}
if (isVNode(node)) {
return openTag(node) + tagContent(node) + closeTag(node);
} else if (isVText(node)) {
if (parent && (parent.tagName.toLowerCase() === 'script'
|| parent.tagName.toLowerCase() === 'style'))
return String(node.text);
return escape(String(node.text));
}
return '';
}
function openTag(node) {
var props = node.properties;
var ret = '<' + node.tagName.toLowerCase();
for (var name in props) {
var value = props[name];
if (value == null) continue;
if (name == 'attributes') {
value = extend({}, value);
for (var attrProp in value) {
ret += ' ' + createAttribute(attrProp, value[attrProp], true);
}
continue;
}
if (name == 'dataset') {
value = extend({}, value);
for (var dataProp in value) {
ret += ' ' + createAttribute('data-' + paramCase(dataProp), value[dataProp], true);
}
continue;
}
if (name == 'style') {
var css = '';
value = extend({}, value);
for (var styleProp in value) {
css += paramCase(styleProp) + ': ' + value[styleProp] + '; ';
}
value = css.trim();
}
if (value instanceof softHook || value instanceof attrHook) {
ret += ' ' + createAttribute(name, value.value, true);
continue;
}
var attr = createAttribute(name, value);
if (attr) ret += ' ' + attr;
}
return ret + '>';
}
function tagContent(node) {
var innerHTML = node.properties.innerHTML;
if (innerHTML != null) return innerHTML;
else {
var ret = '';
if (node.children && node.children.length) {
for (var i = 0, l = node.children.length; i<l; i++) {
var child = node.children[i];
ret += toHTML(child, node);
}
}
return ret;
}
}
function closeTag(node) {
var tag = node.tagName.toLowerCase();
return voidElements[tag] ? '' : '</' + tag + '>';
}