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

ChatMarkdown.tsx

297 lines8.6 KB

1import {
2 getSharedHighlighter,
3 type DiffsHighlighter,
4 type SupportedLanguages,
5} from "@pierre/diffs";
6import { CheckIcon, CopyIcon } from "lucide-react";
7import React, {
8 Children,
9 Suspense,
10 isValidElement,
11 use,
12 useCallback,
13 memo,
14 useEffect,
15 useMemo,
16 useRef,
17 useState,
18 type ReactNode,
19} from "react";
20import type { Components } from "react-markdown";
21import ReactMarkdown from "react-markdown";
22import remarkGfm from "remark-gfm";
23import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
24import { fnv1a32 } from "../lib/diffRendering";
25import { LRUCache } from "../lib/lruCache";
26import { useTheme } from "../hooks/useTheme";
27import { resolveMarkdownFileLinkTarget } from "../markdown-links";
28import { readNativeApi } from "../nativeApi";
29import { preferredTerminalEditor } from "../terminal-links";
30​
31class CodeHighlightErrorBoundary extends React.Component<
32 { fallback: ReactNode; children: ReactNode },
33 { hasError: boolean }
34> {
35 constructor(props: { fallback: ReactNode; children: ReactNode }) {
36 super(props);
37 this.state = { hasError: false };
38 }
39​
40 static getDerivedStateFromError() {
41 return { hasError: true };
42 }
43​
44 override render() {
45 if (this.state.hasError) {
46 return this.props.fallback;
47 }
48 return this.props.children;
49 }
51​
52interface ChatMarkdownProps {
53 text: string;
54 cwd: string | undefined;
55 isStreaming?: boolean;
57​
58const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
59const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
60const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
61const highlightedCodeCache = new LRUCache<string>(
62 MAX_HIGHLIGHT_CACHE_ENTRIES,
63 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
64);
65const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
66​
67function extractFenceLanguage(className: string | undefined): string {
68 const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
69 return match?.[1] ?? "text";
71​
72function nodeToPlainText(node: ReactNode): string {
73 if (typeof node === "string" || typeof node === "number") {
74 return String(node);
75 }
76 if (Array.isArray(node)) {
77 return node.map((child) => nodeToPlainText(child)).join("");
78 }
79 if (isValidElement<{ children?: ReactNode }>(node)) {
80 return nodeToPlainText(node.props.children);
81 }
82 return "";
84​
85function extractCodeBlock(
86 children: ReactNode,
87): { className: string | undefined; code: string } | null {
88 const childNodes = Children.toArray(children);
89 if (childNodes.length !== 1) {
90 return null;
91 }
92​
93 const onlyChild = childNodes[0];
94 if (
95 !isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
96 onlyChild.type !== "code"
97 ) {
98 return null;
99 }
100​
101 return {
102 className: onlyChild.props.className,
103 code: nodeToPlainText(onlyChild.props.children),
104 };
106​
107function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
108 return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
110​
111function estimateHighlightedSize(html: string, code: string): number {
112 return Math.max(html.length * 2, code.length * 3);
114​
115function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
116 const cached = highlighterPromiseCache.get(language);
117 if (cached) return cached;
118​
119 const promise = getSharedHighlighter({
120 themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
121 langs: [language as SupportedLanguages],
122 preferredHighlighter: "shiki-js",
123 }).catch((err) => {
124 highlighterPromiseCache.delete(language);
125 if (language === "text") {
126 // "text" itself failed — Shiki cannot initialize at all, surface the error
127 throw err;
128 }
129 // Language not supported by Shiki — fall back to "text"
130 return getHighlighterPromise("text");
131 });
132 highlighterPromiseCache.set(language, promise);
133 return promise;
135​
136function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
137 const [copied, setCopied] = useState(false);
138 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
139 const handleCopy = useCallback(() => {
140 if (typeof navigator === "undefined" || navigator.clipboard == null) {
141 return;
142 }
143 void navigator.clipboard
144 .writeText(code)
145 .then(() => {
146 if (copiedTimerRef.current != null) {
147 clearTimeout(copiedTimerRef.current);
148 }
149 setCopied(true);
150 copiedTimerRef.current = setTimeout(() => {
151 setCopied(false);
152 copiedTimerRef.current = null;
153 }, 1200);
154 })
155 .catch(() => undefined);
156 }, [code]);
157​
158 useEffect(
159 () => () => {
160 if (copiedTimerRef.current != null) {
161 clearTimeout(copiedTimerRef.current);
162 copiedTimerRef.current = null;
163 }
164 },
165 [],
166 );
167​
168 return (
169 <div className="chat-markdown-codeblock">
170 <button
171 type="button"
172 className="chat-markdown-copy-button"
173 onClick={handleCopy}
174 title={copied ? "Copied" : "Copy code"}
175 aria-label={copied ? "Copied" : "Copy code"}
176 >
177 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
178 </button>
179 {children}
180 </div>
181 );
183​
184interface SuspenseShikiCodeBlockProps {
185 className: string | undefined;
186 code: string;
187 themeName: DiffThemeName;
188 isStreaming: boolean;
190​
191function SuspenseShikiCodeBlock({
192 className,
193 code,
194 themeName,
195 isStreaming,
196}: SuspenseShikiCodeBlockProps) {
197 const language = extractFenceLanguage(className);
198 const cacheKey = createHighlightCacheKey(code, language, themeName);
199 const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
200​
201 if (cachedHighlightedHtml != null) {
202 return (
203 <div
204 className="chat-markdown-shiki"
205 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
206 />
207 );
208 }
209​
210 const highlighter = use(getHighlighterPromise(language));
211 const highlightedHtml = useMemo(() => {
212 try {
213 return highlighter.codeToHtml(code, { lang: language, theme: themeName });
214 } catch {
215 // If highlighting fails for this language, render as plain text
216 return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
217 }
218 }, [code, highlighter, language, themeName]);
219​
220 useEffect(() => {
221 if (!isStreaming) {
222 highlightedCodeCache.set(
223 cacheKey,
224 highlightedHtml,
225 estimateHighlightedSize(highlightedHtml, code),
226 );
227 }
228 }, [cacheKey, code, highlightedHtml, isStreaming]);
229​
230 return (
231 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
232 );
234​
235function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
236 const { resolvedTheme } = useTheme();
237 const diffThemeName = resolveDiffThemeName(resolvedTheme);
238 const markdownComponents = useMemo<Components>(
239 () => ({
240 a({ node: _node, href, ...props }) {
241 const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
242 if (!targetPath) {
243 return <a {...props} href={href} target="_blank" rel="noreferrer" />;
244 }
245​
246 return (
247 <a
248 {...props}
249 href={href}
250 onClick={(event) => {
251 event.preventDefault();
252 event.stopPropagation();
253 const api = readNativeApi();
254 if (api) {
255 void api.shell.openInEditor(targetPath, preferredTerminalEditor());
256 } else {
257 console.warn("Native API not found. Unable to open file in editor.");
258 }
259 }}
260 />
261 );
262 },
263 pre({ node: _node, children, ...props }) {
264 const codeBlock = extractCodeBlock(children);
265 if (!codeBlock) {
266 return <pre {...props}>{children}</pre>;
267 }
268​
269 return (
270 <MarkdownCodeBlock code={codeBlock.code}>
271 <CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
272 <Suspense fallback={<pre {...props}>{children}</pre>}>
273 <SuspenseShikiCodeBlock
274 className={codeBlock.className}
275 code={codeBlock.code}
276 themeName={diffThemeName}
277 isStreaming={isStreaming}
278 />
279 </Suspense>
280 </CodeHighlightErrorBoundary>
281 </MarkdownCodeBlock>
282 );
283 },
284 }),
285 [cwd, diffThemeName, isStreaming],
286 );
287​
288 return (
289 <div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
290 <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
291 {text}
292 </ReactMarkdown>
293 </div>
294 );
296​
297export default memo(ChatMarkdown);