cohost/html/jsx/jsx-runtime.ts

51 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-07-09 20:51:15 -04:00
import { fr, Html, Prop } from "../html.ts";
2023-07-09 02:34:35 -04:00
type SadProp = Prop | undefined | Html | Html[];
export type Component = (
2023-07-09 20:51:15 -04:00
props: CProps,
2023-07-09 02:34:35 -04:00
children: Html[],
) => Html;
2023-07-09 20:51:15 -04:00
export type CProps = {
[key: string]: any;
};
2023-07-09 02:34:35 -04:00
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: [] };
2023-07-09 20:51:15 -04:00
const children: Html[] = [props.children ?? []].flat().filter((c) =>
typeof c == "string" || typeof c == "object"
);
const attributes: CProps = {};
2023-07-09 02:34:35 -04:00
for (const [key, val] of Object.entries(props)) {
if (
2023-07-09 20:51:15 -04:00
key == "children" || typeof val == "undefined"
2023-07-09 02:34:35 -04:00
) 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;