Open History to see the last commit
1import { toHtml } from "hast-util-to-html";
2import { toJsxRuntime } from "hast-util-to-jsx-runtime";
3import { cloneElement, isValidElement, memo, type DOMAttributes } from "react";
4import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
6import type { highlightCodeToHast } from "../../lib/incrementalHighlighting";
7
8type HighlightedRoot = ReturnType<typeof highlightCodeToHast>;
9type HighlightedNode = HighlightedRoot["children"][number];
10const runtime = { Fragment, jsx, jsxs };
11
12function elementShell(node: Extract<HighlightedNode, { type: "element" }>) {
13 const element = toJsxRuntime({ ...node, children: [] }, runtime);
14 if (!isValidElement<DOMAttributes<HTMLElement>>(element)) {
15 throw new Error("Expected a highlighted code element");
16 }
17 return element;
18}
19
20const HighlightedLine = memo(function HighlightedLine({ node }: { node: HighlightedNode }) {
21 if (node.type !== "element") return toJsxRuntime(node, runtime);
22 return cloneElement(elementShell(node), {
23 dangerouslySetInnerHTML: { __html: toHtml({ type: "root", children: node.children }) },
24 });
25});
26
27/** Preserve completed lines' DOM to avoid reparsing unchanged tokens. */
28export function HighlightedCodeLines({ root }: { root: HighlightedRoot }) {
29 const pre = root.children[0];
30 if (pre?.type !== "element" || pre.tagName !== "pre") return toJsxRuntime(root, runtime);
31 const code = pre.children[0];
32 if (code?.type !== "element" || code.tagName !== "code") return toJsxRuntime(root, runtime);
33 return cloneElement(
34 elementShell(pre),
35 undefined,
36 cloneElement(
37 elementShell(code),
38 undefined,
39 code.children.map((node, index) => (
40 // Appending tokens and lines preserves line positions.
41 // oxlint-disable-next-line react/no-array-index-key
42 <HighlightedLine key={index} node={node} />
43 )),
44 ),
45 );
46}