-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathstringify.js
More file actions
50 lines (42 loc) · 1.06 KB
/
stringify.js
File metadata and controls
50 lines (42 loc) · 1.06 KB
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
import emptyTags from './empty-tags';
// escape an attribute
let esc = str => String(str).replace(/[&<>"']/g, s=>`&${map[s]};`);
let map = {'&':'amp','<':'lt','>':'gt','"':'quot',"'":'apos'};
let DOMAttributeNames = {
className: 'class',
htmlFor: 'for'
};
let sanitized = {};
export default function stringify(name, attrs, stack) {
// Sortof component support!
if (typeof name==='function') {
attrs.children = stack.reverse();
return String(name(attrs));
}
let s = `<${name}`;
if (attrs) for (let i in attrs) {
if (attrs[i]!==false && attrs[i]!=null) {
s += ` ${DOMAttributeNames[i] ? DOMAttributeNames[i] : esc(i)}="${esc(attrs[i])}"`;
}
}
if (emptyTags.indexOf(name) === -1) {
s += '>';
while (stack.length) {
let child = stack.pop();
if (child) {
if (child.pop) {
for (let i=child.length; i--; ) stack.push(child[i]);
}
else {
let resolved = String(child);
s += sanitized[resolved]===true ? resolved : esc(resolved);
}
}
}
s += `</${name}>`;
} else {
s += '>';
}
sanitized[s] = true;
return s;
}