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

useHighlightedCode.ts

149 lines4.6 KB

1import { useEffect, useMemo, useRef, useState } from "react";
2​
3import { pendingCodeHighlight } from "./pendingCodeHighlight";
4import type {
5 MarkdownCodeHighlighter,
6 MarkdownHighlightedToken,
7} from "./SelectableMarkdownText.types";
8​
9export type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
10​
11interface HighlightedCodeResult {
12 readonly key: string;
13 readonly code: string;
14 readonly language: string | undefined;
15 readonly theme: "light" | "dark";
16 readonly tokens: HighlightedCode | null;
18​
19const highlightedCodeCache = new Map<string, HighlightedCode>();
20const highlightedCodePromiseCache = new Map<string, Promise<HighlightedCode>>();
21const HIGHLIGHTED_CODE_CACHE_LIMIT = 64;
22​
23function codeHighlightCacheKey(
24 code: string,
25 language: string | undefined,
26 theme: "light" | "dark",
27): string {
28 return `${theme}:${language ?? "text"}:${code}`;
30​
31function cacheHighlightedCode(key: string, tokens: HighlightedCode): void {
32 highlightedCodeCache.delete(key);
33 highlightedCodeCache.set(key, tokens);
34​
35 while (highlightedCodeCache.size > HIGHLIGHTED_CODE_CACHE_LIMIT) {
36 const oldestKey = highlightedCodeCache.keys().next().value;
37 if (oldestKey === undefined) {
38 break;
39 }
40 highlightedCodeCache.delete(oldestKey);
41 }
43​
44function loadHighlightedCode(
45 code: string,
46 language: string | undefined,
47 theme: "light" | "dark",
48 highlightCode: MarkdownCodeHighlighter,
49 session: object,
50): Promise<HighlightedCode> {
51 const key = codeHighlightCacheKey(code, language, theme);
52 const cached = highlightedCodeCache.get(key);
53 if (cached) {
54 return Promise.resolve(cached);
55 }
56​
57 const pending = highlightedCodePromiseCache.get(key);
58 if (pending) {
59 return pending;
60 }
61​
62 const promise = highlightCode({ code, language, theme, session })
63 .then((tokens) => {
64 cacheHighlightedCode(key, tokens);
65 highlightedCodePromiseCache.delete(key);
66 return tokens;
67 })
68 .catch((error) => {
69 highlightedCodePromiseCache.delete(key);
70 throw error;
71 });
72 highlightedCodePromiseCache.set(key, promise);
73 return promise;
75​
76/**
77 * Tokens for a code block, or null while nothing usable exists yet. A cached or
78 * synchronous result renders in the same pass. Otherwise the most recent
79 * completed result seeds `pendingCodeHighlight` so finished lines keep their
80 * colors while the asynchronous highlighter catches up.
81 */
82export function useHighlightedCode(
83 code: string,
84 language: string | undefined,
85 theme: "light" | "dark",
86 highlightCode: MarkdownCodeHighlighter,
87): HighlightedCode | null {
88 const [session] = useState(() => ({}));
89 const key = codeHighlightCacheKey(code, language, theme);
90 const ready = useMemo(
91 () => highlightedCodeCache.get(key) ?? highlightCode.read?.({ code, language, theme, session }),
92 [code, language, theme, key, highlightCode, session],
93 );
94 const [highlighted, setHighlighted] = useState<HighlightedCodeResult>(() => ({
95 code,
96 language,
97 theme,
98 key,
99 tokens: highlightedCodeCache.get(key) ?? null,
100 }));
101 // Synchronous reads never touch state, so each append costs one render. The
102 // ref remembers the newest of them, and is cleared whenever an asynchronous
103 // result commits so `highlighted` is the baseline again from then on.
104 const latestRead = useRef<HighlightedCodeResult | null>(null);
105​
106 useEffect(() => {
107 if (ready) {
108 latestRead.current = { code, language, theme, key, tokens: ready };
109 return;
110 }
111 let active = true;
112 const commit = (tokens: HighlightedCode | null) => {
113 latestRead.current = null;
114 setHighlighted({ code, language, theme, key, tokens });
115 };
116 const cached = highlightedCodeCache.get(key);
117 if (cached) {
118 cacheHighlightedCode(key, cached);
119 commit(cached);
120 return () => {
121 active = false;
122 };
123 }
124​
125 void loadHighlightedCode(code, language, theme, highlightCode, session)
126 .then((tokens) => {
127 if (active) {
128 commit(tokens);
129 }
130 })
131 .catch(() => {
132 if (active) {
133 commit(null);
134 }
135 });
136 return () => {
137 active = false;
138 };
139 }, [code, highlightCode, key, language, theme, ready, session]);
140​
141 if (ready) return ready;
142 // oxlint-disable-next-line react/refs -- Written only after commit; a discarded render never advances it.
143 const baseline = latestRead.current ?? highlighted;
144 if (baseline.key === key) return baseline.tokens;
145 if (baseline.tokens && baseline.language === language && baseline.theme === theme) {
146 return pendingCodeHighlight(baseline.code, code, baseline.tokens);
147 }
148 return null;