-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrender-to-string.js
59 lines (48 loc) · 1.56 KB
/
render-to-string.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
const {html} = require('diffhtml');
const {registry} = require('./custom-elements');
const attrsToString = attrs => attrs.map(
({name, value}) => ` ${name}="${value}"`
).join('');
const findAttr = (node, attr) => node.attributes.find(({name}) => name === attr) || {};
const hasAttr = (node, attr) => !!(findAttr(node, attr).name);
const getAttr = (node, attr) => findAttr(node, attr).value;
const setAttr = (node, attr, value) => {
const attrObj = findAttr(node, attr);
if(attrObj.name) {
attrObj.value = value;
} else {
node.attributes.push({name: attr, value});
}
}
const root = Symbol('root');
module.exports = function renderToString(node, slotMap = new Map()) {
if(registry.has(node.nodeName)) {
const Class = registry.get(node.nodeName);
const element = new Class(node);
node.slots = new Map();
node.childNodes.forEach(child => {
const slot = getAttr(child, 'slot') || root;
if(node.slots.has(slot)) {
node.slots.get(slot).push(child);
} else {
node.slots.set(slot, [child]);
}
});
node.childNodes = [].concat(html`<span slot="__excise_rendered">
${element.render(element.props, element)}
</span>`, node.childNodes);
}
if(node.nodeName === 'slot') {
const slotName = getAttr(node, 'name') || root;
node.childNodes = [].concat(slotMap.get(slotName) || []);
}
const children = node.childNodes.map(
child => renderToString(child, node.slots || slotMap)
);
if(node.nodeName === '#text') {
return node.nodeValue;
}
return `<${node.nodeName}${attrsToString(node.attributes)}>
${children.join('')}
</${node.nodeName}>`
}