Last active
June 6, 2022 20:50
-
-
Save usualoma/26e17a61fab123adcc7408eb00279e6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare global { | |
// eslint-disable-next-line @typescript-eslint/no-namespace | |
namespace jsx.JSX { | |
interface IntrinsicElements { | |
[tagName: string]: Record<string, string>; | |
} | |
} | |
} | |
class EscapedString { | |
private content: string; | |
constructor(content: string) { | |
this.content = content; | |
} | |
public toString() { | |
return this.content; | |
} | |
} | |
function escape(str: string): string { | |
return str | |
.replace(/&/g, "&") | |
.replace(/"/g, """) | |
.replace(/'/g, "'") | |
.replace(/</g, "<") | |
.replace(/>/g, ">"); | |
} | |
export function jsx( | |
tag: string | Function, | |
props: Record<string, string | EscapedString>, | |
...children: (string | EscapedString)[] | |
): EscapedString { | |
if (typeof tag === "function") { | |
props ||= {}; | |
props["children"] = children[0]; | |
return tag(props, children); | |
} | |
let attrs = ""; | |
const propsKeys = Object.keys(props || {}); | |
for (let i = 0, len = propsKeys.length; i < len; i++) { | |
attrs += ` ${propsKeys[i]}="${escape(props[propsKeys[i]])}"`; | |
} | |
return new EscapedString( | |
`<${tag}${attrs}>${children | |
.map((c) => (c instanceof EscapedString ? c.toString() : escape(c))) | |
.join("")}</${tag}>` | |
); | |
} | |
export function render(content: EscapedString): string { | |
return content.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment