-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrenderer.ts
23 lines (23 loc) · 1.19 KB
/
renderer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function render(element: JSX.Element | string | null): string {
if (element == null) return '';
if (typeof element !== "object") element = String(element);
if (typeof element === "string") return element.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
//if (element instanceof Raw) return element.html;
console.assert(!!element.attributes, 'Element attributes must be defined:\n' + JSON.stringify(element));
const elementAttributes = element.attributes;
let attributes = Object.keys(elementAttributes).filter(key => {
const value = (elementAttributes as any)[key];
return value != null;
}).map(key => {
const value = (elementAttributes as any)[key];
if (value === true) {
return key;
}
return `${key}="${String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')}"`;
}).join(' ');
if (attributes.length > 0) {
attributes = ' ' + attributes;
}
const children = element.children.length > 0 ? `>${element.children.map(child => render(child)).join('')}` : '>';
return `<${element.name}${attributes}${children}</${element.name}>`;
}