2022-11-01 14:01:28 +00:00
|
|
|
export const Fragment = "FRAGMENT";
|
|
|
|
|
|
|
|
export type Tag = {
|
|
|
|
name: string;
|
|
|
|
attrs?: Record<string, string | undefined>;
|
|
|
|
body: Tag[] | string;
|
|
|
|
} | string;
|
|
|
|
|
|
|
|
function htmlEscape(s: string): string {
|
2023-10-29 11:10:30 +00:00
|
|
|
s = s.replace(/&/g, "&")
|
2022-11-01 14:01:28 +00:00
|
|
|
.replace(/</g, "<")
|
|
|
|
.replace(/>/g, ">")
|
2023-10-29 11:10:30 +00:00
|
|
|
.replace(/"/g, """)
|
|
|
|
.replace(/\n/g, "<br>");
|
|
|
|
|
|
|
|
let oldS = s;
|
|
|
|
do {
|
|
|
|
oldS = s;
|
|
|
|
s = s.replace(/ /g, " ");
|
|
|
|
} while (s !== oldS);
|
|
|
|
return s;
|
2022-11-01 14:01:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function renderHtml(t: Tag | null): string {
|
|
|
|
if (!t) {
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
if (typeof t === "string") {
|
|
|
|
return htmlEscape(t);
|
|
|
|
}
|
|
|
|
const attrs = t.attrs
|
|
|
|
? " " + Object.entries(t.attrs)
|
|
|
|
.filter(([, value]) => value !== undefined)
|
|
|
|
.map(([k, v]) => `${k}="${htmlEscape(v!)}"`).join(
|
|
|
|
" ",
|
|
|
|
)
|
|
|
|
: "";
|
|
|
|
const body = typeof t.body === "string"
|
|
|
|
? htmlEscape(t.body)
|
|
|
|
: t.body.map(renderHtml).join("");
|
|
|
|
if (t.name === Fragment) {
|
|
|
|
return body;
|
|
|
|
}
|
2023-10-29 11:10:30 +00:00
|
|
|
// if (t.body) {
|
|
|
|
return `<${t.name}${attrs}>${body}</${t.name}>`;
|
|
|
|
// } else {
|
|
|
|
// return `<${t.name}${attrs}/>`;
|
|
|
|
// }
|
2022-11-01 14:01:28 +00:00
|
|
|
}
|