Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownIslands.ts

214 lines7.4 KB

1import type { Element, ElementContent, Properties, Root, RootContent } from "hast";
2import { find, html as htmlSchema, svg as svgSchema } from "property-information";
3import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime";
4import { createElement, Fragment as ReactFragment, type ReactNode } from "react";
5import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6​
7export interface MarkdownIslandOptions {
8 readonly components: Partial<Components>;
9 /** Elements that need their React component; everything else renders as static HTML. */
10 readonly isIsland: (node: Element) => boolean;
11 /** What a static element's component would have added, or the node itself when nothing. */
12 readonly staticElement: (node: Element) => Element;
13 /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */
14 readonly variant: string;
16​
17const VOID_ELEMENTS = new Set(
18 "area base br col embed hr img input link meta source track wbr".split(" "),
19);
20​
21const jsxOptions = (components: Partial<Components>) =>
22 ({
23 Fragment,
24 components,
25 ignoreInvalidStyle: true,
26 jsx,
27 jsxs,
28 passKeys: true,
29 passNode: true,
30 }) as const;
31​
32// Static HTML depends only on the cached, immutable tree and the variant.
33const innerHtmlCache = new WeakMap<Element, { variant: string; html: string }>();
34​
35function transformStatic(
36 node: ElementContent,
37 staticElement: MarkdownIslandOptions["staticElement"],
38): ElementContent {
39 if (node.type !== "element") return node;
40 const element = staticElement(node);
41 let children: ElementContent[] | undefined;
42 for (let index = 0; index < element.children.length; index++) {
43 const child = element.children[index]!;
44 const next = transformStatic(child, staticElement);
45 if (next !== child) {
46 children ??= element.children.slice();
47 children[index] = next;
48 }
49 }
50 return children ? { ...element, children } : element;
52​
53function innerHtml(node: Element, options: MarkdownIslandOptions): string {
54 const cached = innerHtmlCache.get(node);
55 if (cached?.variant === options.variant) return cached.html;
56 let html = "";
57 for (const child of node.children) {
58 html += serialize(transformStatic(child, options.staticElement));
59 }
60 innerHtmlCache.set(node, { variant: options.variant, html });
61 return html;
63​
64interface AttributeInfo {
65 readonly name: string;
66 readonly boolean: boolean;
67 readonly separator: string;
69​
70const attributeInfo = new Map<string, AttributeInfo>();
71​
72// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart.
73function infoFor(property: string, inSvg: boolean): AttributeInfo {
74 const key = inSvg ? `svg:${property}` : property;
75 let info = attributeInfo.get(key);
76 if (!info) {
77 const found = find(inSvg ? svgSchema : htmlSchema, property);
78 info = {
79 name: found.attribute,
80 boolean: found.boolean || found.overloadedBoolean,
81 separator: found.commaSeparated ? ", " : " ",
82 };
83 attributeInfo.set(key, info);
84 }
85 return info;
87​
88const escapeText = (value: string) =>
89 value.includes("&") || value.includes("<") || value.includes(">")
90 ? value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
91 : value;
92const escapeAttribute = (value: string) =>
93 value.includes("&") || value.includes('"')
94 ? value.replace(/&/g, "&amp;").replace(/"/g, "&quot;")
95 : value;
96​
97/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */
98function serialize(node: ElementContent, inSvg = false): string {
99 if (node.type === "text") return escapeText(node.value);
100 if (node.type !== "element") return "";
101 const svg = inSvg || node.tagName === "svg";
102 let html = `<${node.tagName}`;
103 const { properties } = node;
104 for (const key in properties) {
105 const value = properties[key];
106 if (value === null || value === undefined || value === false || Number.isNaN(value)) continue;
107 const info = infoFor(key, svg);
108 if (info.boolean && value) {
109 html += ` ${info.name}`;
110 continue;
111 }
112 const text = Array.isArray(value)
113 ? value.join(info.separator)
114 : value === true
115 ? ""
116 : String(value);
117 html += ` ${info.name}="${escapeAttribute(text)}"`;
118 }
119 html += ">";
120 if (VOID_ELEMENTS.has(node.tagName)) return html;
121 for (const child of node.children) html += serialize(child, svg);
122 return `${html}</${node.tagName}>`;
124​
125/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */
126function shallowProps(node: Element, components: Partial<Components>): Record<string, unknown> {
127 const element = toJsxRuntime(
128 { ...node, children: [] },
129 { ...jsxOptions(components), components: {}, passNode: false },
130 ) as { props: Record<string, unknown> };
131 const { children: _children, ...props } = element.props;
132 return props;
134​
135interface Plan {
136 readonly islands: Set<Element>;
137 /** Elements with an island somewhere below them. */
138 readonly ancestors: Set<Element>;
140​
141function renderContent(
142 node: RootContent,
143 key: number,
144 options: MarkdownIslandOptions,
145 plan: Plan,
146): ReactNode {
147 if (node.type === "text") return node.value;
148 if (node.type !== "element") return null;
149 if (plan.islands.has(node)) {
150 return createElement(
151 ReactFragment,
152 { key },
153 toJsxRuntime(node, jsxOptions(options.components)),
154 );
155 }
156 const element = options.staticElement(node);
157 const props: Record<string, unknown> = { ...shallowProps(element, options.components), key };
158 if (plan.ancestors.has(node)) {
159 return createElement(
160 element.tagName,
161 props,
162 ...element.children.map((child, index) => renderContent(child, index, options, plan)),
163 );
164 }
165 if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) {
166 props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) };
167 }
168 return createElement(element.tagName, props);
170​
171/**
172 * Renders a hast tree with React only on the path to elements that need a component: subtrees
173 * without one become static HTML, which the browser builds without React reconciling each node.
174 */
175export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode {
176 // The same elements again let React skip the block; islands still follow their context.
177 let signature = options.variant;
178 const plan: Plan = { islands: new Set(), ancestors: new Set() };
179 const visit = (node: Root | Element): boolean => {
180 let below = false;
181 for (const child of node.children) {
182 if (child.type !== "element") continue;
183 const island = options.isIsland(child);
184 signature += island ? "1" : "0";
185 if (island) {
186 plan.islands.add(child);
187 below = true;
188 continue;
189 }
190 if (visit(child)) {
191 plan.ancestors.add(child);
192 below = true;
193 }
194 }
195 return below;
196 };
197 visit(tree);
198 const cached = renderedTrees.get(tree);
199 if (cached?.signature === signature && cached.components === options.components) {
200 return cached.node;
201 }
202 const node = tree.children.map((child, index) => renderContent(child, index, options, plan));
203 renderedTrees.set(tree, { signature, components: options.components, node });
204 return node;
206​
207const renderedTrees = new WeakMap<
208 Root,
209 { signature: string; components: Partial<Components>; node: ReactNode }
210>();
211​
212export function withProperties(node: Element, properties: Properties): Element {
213 return { ...node, properties: { ...node.properties, ...properties } };