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