summaryrefslogtreecommitdiffhomepage
path: root/services/blog/nuldoc-src/jsx/render.ts
blob: a72d9ad7fa6783002285463f20a6222c9ea7e6d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import type { Element, Node } from "../dom.ts";
import { elem, text } from "../dom.ts";
import type {
  JSXNode,
  JSXNullableSimpleNode,
  JSXSimpleNode,
  RenderableJSXNode,
} from "myjsx/jsx-runtime";

function transformNode(node: JSXNode): Promise<Node[]> {
  const flattenNodes: JSXNullableSimpleNode[] = Array.isArray(node)
    // @ts-ignore prevents infinite recursion
    ? (node.flat(Infinity) as JSXNullableSimpleNode[])
    : [node];
  return Promise.all(
    flattenNodes
      .filter((c): c is JSXSimpleNode => c != null && c !== false)
      .map((c) => {
        if (typeof c === "string") {
          return text(c);
        } else if ("kind" in c) {
          return c;
        } else {
          return renderToDOM(c);
        }
      }),
  );
}

export async function renderToDOM(
  element: RenderableJSXNode,
): Promise<Element> {
  const { tag, props } = element;
  if (typeof tag === "string") {
    const { children, ...attrs } = props;
    const attrsMap = attrs as Record<string, string>;
    return elem(tag, attrsMap, ...(await transformNode(children)));
  } else {
    return renderToDOM(await tag(props));
  }
}