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

markdownRenderer.ts

102 lines3.3 KB

1import type { Element, Nodes, Root } from "hast";
2import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime";
3import { urlAttributes } from "html-url-attributes";
4import type { ReactElement } from "react";
5import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6​
7import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast";
8​
9export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string;
10​
11interface MarkdownRendererOptions {
12 readonly markdown: WordsHastOptions;
13 readonly components: Partial<Components>;
14 readonly urlTransform: MarkdownUrlTransform;
16​
17// Elements are immutable, so a remount (a thread switch, a row scrolled back into view)
18// reuses one instead of parsing again. Parsing is most of the cost of rendering markdown.
19// An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB.
20const MAX_CACHED_CHARS = 500_000;
21interface Rendered {
22 readonly tree: Root;
23 element?: ReactElement;
25const rendered = new Map<string, Rendered>();
26let cachedChars = 0;
27let nextRendererId = 0;
28​
29// A short block still holds a whole element tree.
30const ENTRY_OVERHEAD_CHARS = 200;
31const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS;
32​
33function remember(key: string, entry: Rendered) {
34 // One huge message would otherwise evict everything else.
35 if (entrySize(key) > MAX_CACHED_CHARS / 4) return;
36 rendered.set(key, entry);
37 cachedChars += entrySize(key);
38 for (const oldest of rendered.keys()) {
39 if (cachedChars <= MAX_CACHED_CHARS) break;
40 rendered.delete(oldest);
41 cachedChars -= entrySize(oldest);
42 }
44​
45/** Renders markdown with Words, keeping one parse cache per option set. */
46export function createMarkdownRenderer({
47 markdown,
48 components,
49 urlTransform,
50}: MarkdownRendererOptions) {
51 const keyPrefix = `${nextRendererId++}\u0000`;
52​
53 // URL attributes, as react-markdown transformed them.
54 const prepare = (node: Nodes) => {
55 if (!("children" in node)) return;
56 for (const child of node.children) {
57 if (child.type !== "element") continue;
58 const { properties } = child;
59 for (const key in properties) {
60 if (!Object.hasOwn(urlAttributes, key)) continue;
61 const tags = urlAttributes[key];
62 if (tags === null || tags?.includes(child.tagName)) {
63 properties[key] = urlTransform(String(properties[key] || ""), key, child);
64 }
65 }
66 prepare(child);
67 }
68 };
69​
70 const parse = (text: string): Rendered => {
71 const key = keyPrefix + text;
72 const cached = rendered.get(key);
73 if (cached !== undefined) {
74 // Refresh its place in the eviction order.
75 rendered.delete(key);
76 rendered.set(key, cached);
77 return cached;
78 }
79 const tree = wordsHast(text, markdown);
80 prepare(tree);
81 return { tree };
82 };
83​
84 return {
85 /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */
86 parse,
87 element: (entry: Rendered): ReactElement =>
88 (entry.element ??= toJsxRuntime(entry.tree, {
89 Fragment,
90 components,
91 ignoreInvalidStyle: true,
92 jsx,
93 jsxs,
94 passKeys: true,
95 passNode: true,
96 })),
97 remember(text: string, entry: Rendered) {
98 const key = keyPrefix + text;
99 if (!rendered.has(key)) remember(key, entry);
100 },
101 };