Render a JSON node tree as indented HTML markup
An email builder stores each template as a tree of plain objects, so it can be saved as JSON and edited in a visual editor. Before sending, the tree has to become readable, indented HTML. Implement renderMarkup(node, indentSize), which turns a tree into an HTML string.
renderMarkup(node, indentSize = 2) // => string
{ tag, attrs?, children? }. tag is a lowercase tag name, attrs is a plain object, and children is an array of nodes. Both attrs and children are optional.depth * indentSize spaces. The root has depth 0, its children depth 1, and so on.'\n'. There is no trailing newline.children are skipped, as if they were not there.<td></td>.<h1>Welcome</h1>.area, br, col, hr, img, input, link, meta) render only their opening tag, such as <br>, with no closing tag. Their children are ignored.attrs, each as name="value". Numbers are converted with String.true renders the bare name, such as disabled.false, null, and undefined omit the attribute.& with &, < with <, and > with >." with ".renderMarkup({
tag: 'table',
attrs: { role: 'presentation', width: 600 },
children: [
{
tag: 'tr',
children: [
{ tag: 'td', attrs: { class: 'logo' }, children: [{ tag: 'img', attrs: { src: 'logo.png', alt: 'Tom & Co' } }] },
{ tag: 'td', children: ['Order ', { tag: 'b', children: ['#1042'] }, ' shipped'] },
{ tag: 'td', attrs: { hidden: true, title: null } },
],
},
],
});
returns:
<table role="presentation" width="600">
<tr>
<td class="logo">
<img src="logo.png" alt="Tom & Co">
</td>
<td>
Order
<b>#1042</b>
shipped
</td>
<td hidden></td>
</tr>
</table>
Text is never trimmed: 'Order ' keeps its trailing space and ' shipped' its leading space, after the indentation.
renderMarkup('Fish & chips'); // => 'Fish & chips'
renderMarkup({ tag: 'p', children: ['Hi'] }, 4); // => '<p>Hi</p>'
renderMarkup({ tag: 'ul', children: [{ tag: 'li', children: ['One'] }] }, 4);
// => '<ul>\n <li>One</li>\n</ul>'