Skip to content

Instantly share code, notes, and snippets.

@usualoma
Last active October 18, 2023 20:57
Show Gist options
  • Save usualoma/cec18e230e35738b80c74a54014deb00 to your computer and use it in GitHub Desktop.
Save usualoma/cec18e230e35738b80c74a54014deb00 to your computer and use it in GitHub Desktop.
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jsx.JSX {
interface IntrinsicElements {
[tagName: string]: Record<string, string>;
}
}
}
function escape(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
export function jsx(
tag: string | Function,
props: Record<string, string | string[]>,
...children: (string | string[])[]
): string[] {
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]] as string)}"`;
}
return [
`<${tag}${attrs}>`,
...children.map((c) => (typeof c === "string" ? escape(c) : c)).flat(),
`</${tag}>`,
];
}
export function render(content: string[]): string {
return content.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment