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

markdownParseCache.ts

135 lines4.3 KB

1import type { Root } from "mdast";
2​
3const MAX_AST_ENTRIES = 192;
4const MAX_RENDERED_ENTRIES = 256;
5const MAX_CACHEABLE_LENGTH = 131_072;
6​
7const astCache = new Map<string, Root>();
8const renderedMarkdownCache = new Map<string, string>();
9const linkUrlsCache = new Map<string, readonly string[]>();
10​
11export const EMPTY_FILE_HREFS: ReadonlySet<string> = new Set<string>();
12export const EMPTY_LINK_URLS: readonly string[] = [];
13​
14const LINK_CANDIDATE_RE = /(?:\]\(|\]\[|\]:|https?:\/\/|www\.|mailto:|t3-|<[a-z][a-z0-9+.-]*:)/i;
15​
16function hasEmailCandidate(markdown: string): boolean {
17 let at = markdown.indexOf("@");
18 while (at !== -1) {
19 if (
20 at > 0 &&
21 at + 1 < markdown.length &&
22 !/[\s@]/.test(markdown[at - 1]!) &&
23 !/[\s@]/.test(markdown[at + 1]!)
24 ) {
25 return true;
26 }
27 at = markdown.indexOf("@", at + 1);
28 }
29 return false;
31​
32interface MdastNodeLike {
33 readonly type: string;
34 readonly url?: string;
35 readonly identifier?: string;
36 readonly children?: ReadonlyArray<MdastNodeLike>;
38​
39function lruGet<V>(cache: Map<string, V>, key: string): V | undefined {
40 const hit = cache.get(key);
41 if (hit === undefined) return undefined;
42 cache.delete(key);
43 cache.set(key, hit);
44 return hit;
46​
47function lruSet<V>(cache: Map<string, V>, key: string, value: V, maxEntries: number): void {
48 if (cache.has(key)) {
49 cache.delete(key);
50 } else if (cache.size >= maxEntries) {
51 const oldest = cache.keys().next().value;
52 if (oldest !== undefined) cache.delete(oldest);
53 }
54 cache.set(key, value);
56​
57export function getCachedMarkdownAst(markdown: string, parse: (input: string) => Root): Root {
58 if (markdown.length > MAX_CACHEABLE_LENGTH) return parse(markdown);
59 const hit = lruGet(astCache, markdown);
60 if (hit !== undefined) return hit;
61 const parsed = parse(markdown);
62 lruSet(astCache, markdown, parsed, MAX_AST_ENTRIES);
63 return parsed;
65​
66export function getCachedNativeMarkdown(
67 markdown: string,
68 compute: (input: string) => string,
69): string {
70 if (markdown.length > MAX_CACHEABLE_LENGTH) return compute(markdown);
71 const hit = lruGet(renderedMarkdownCache, markdown);
72 if (hit !== undefined) return hit;
73 const rendered = compute(markdown);
74 lruSet(renderedMarkdownCache, markdown, rendered, MAX_RENDERED_ENTRIES);
75 return rendered;
77​
78// Seeds EnrichedMarkdownText linkVariants/linkPillContent on render 1 so Android does not
79// recreate all native segment views after useLayoutEffect reports onLinksChange.
80export function getCachedMarkdownLinkUrls(
81 markdown: string,
82 parse: (input: string) => Root,
83): readonly string[] {
84 if (
85 markdown.length === 0 ||
86 (!LINK_CANDIDATE_RE.test(markdown) && !hasEmailCandidate(markdown))
87 ) {
88 return EMPTY_LINK_URLS;
89 }
90 const cacheable = markdown.length <= MAX_CACHEABLE_LENGTH;
91 if (cacheable) {
92 const hit = lruGet(linkUrlsCache, markdown);
93 if (hit !== undefined) return hit;
94 }
95 const root = parse(markdown) as unknown as MdastNodeLike;
96 let definitions: Map<string, string> | null = null;
97 if (markdown.includes("]:")) {
98 definitions = new Map<string, string>();
99 const collectDefs = (node: MdastNodeLike) => {
100 if (node.type === "definition" && node.identifier && typeof node.url === "string") {
101 const id = node.identifier.toUpperCase();
102 if (!definitions!.has(id)) definitions!.set(id, node.url);
103 }
104 if (node.children) {
105 for (let i = 0; i < node.children.length; i++) collectDefs(node.children[i]!);
106 }
107 };
108 collectDefs(root);
109 }
110 const seen = new Set<string>();
111 const urls: string[] = [];
112 const visit = (node: MdastNodeLike) => {
113 if (node.type === "link" && typeof node.url === "string") {
114 if (!seen.has(node.url)) {
115 seen.add(node.url);
116 urls.push(node.url);
117 }
118 } else if (node.type === "linkReference" && node.identifier && definitions !== null) {
119 const resolved = definitions.get(node.identifier.toUpperCase());
120 if (resolved !== undefined && !seen.has(resolved)) {
121 seen.add(resolved);
122 urls.push(resolved);
123 }
124 }
125 if (node.children) {
126 for (let i = 0; i < node.children.length; i++) visit(node.children[i]!);
127 }
128 };
129 visit(root);
130 const result: readonly string[] = urls.length === 0 ? EMPTY_LINK_URLS : urls;
131 if (cacheable) {
132 lruSet(linkUrlsCache, markdown, result, MAX_RENDERED_ENTRIES);
133 }
134 return result;