cohost/html/jsx/jsx-runtime.ts
2023-07-09 20:51:15 -04:00

51 lines
1.1 KiB
TypeScript

import { fr, Html, Prop } from "../html.ts";
type SadProp = Prop | undefined | Html | Html[];
export type Component = (
props: CProps,
children: Html[],
) => Html;
export type CProps = {
[key: string]: any;
};
interface Props {
[key: string]: typeof key extends "children" ? never : SadProp;
children: undefined | Html | Html[];
}
export function create_element(
type: Component | string,
props_?: Props,
): Html {
const props: Props = props_ ?? { children: [] };
const children: Html[] = [props.children ?? []].flat().filter((c) =>
typeof c == "string" || typeof c == "object"
);
const attributes: CProps = {};
for (const [key, val] of Object.entries(props)) {
if (
key == "children" || typeof val == "undefined"
) continue;
attributes[key] = val;
}
if (typeof type == "string") {
return { tag: type, attributes, children };
} else {
return type(attributes, children);
}
}
export function Fragment(
_: Record<string | number | symbol, never>,
children: Html[],
) {
return fr(...children);
}
export const jsx = create_element;
export const jsxs = create_element;