Open History to see the last commit
1import {
2 getSharedHighlighter,
3 type DiffsHighlighter,
4 type SupportedLanguages,
5} from "@pierre/diffs";
6import { CheckIcon, CopyIcon } from "lucide-react";
7import {
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
31interface ChatMarkdownProps {
32 text: string;
33 cwd: string | undefined;
34 isStreaming?: boolean;
35}
36
37const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
38const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
39const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
40const highlightedCodeCache = new LRUCache<string>(
41 MAX_HIGHLIGHT_CACHE_ENTRIES,
42 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
43);
44const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
45
46function extractFenceLanguage(className: string | undefined): string {
47 const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
48 return match?.[1] ?? "text";
49}
50
51function nodeToPlainText(node: ReactNode): string {
52 if (typeof node === "string" || typeof node === "number") {
53 return String(node);
54 }
55 if (Array.isArray(node)) {
56 return node.map((child) => nodeToPlainText(child)).join("");
57 }
58 if (isValidElement<{ children?: ReactNode }>(node)) {
59 return nodeToPlainText(node.props.children);
60 }
61 return "";
62}
63
64function extractCodeBlock(
65 children: ReactNode,
66): { className: string | undefined; code: string } | null {
67 const childNodes = Children.toArray(children);
68 if (childNodes.length !== 1) {
69 return null;
70 }
71
72 const onlyChild = childNodes[0];
73 if (
74 !isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
75 onlyChild.type !== "code"
76 ) {
77 return null;
78 }
79
80 return {
81 className: onlyChild.props.className,
82 code: nodeToPlainText(onlyChild.props.children),
83 };
84}
85
86function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
87 return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
88}
89
90function estimateHighlightedSize(html: string, code: string): number {
91 return Math.max(html.length * 2, code.length * 3);
92}
93
94function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
95 const cached = highlighterPromiseCache.get(language);
96 if (cached) return cached;
97
98 const promise = getSharedHighlighter({
99 themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
100 langs: [language as SupportedLanguages],
101 preferredHighlighter: "shiki-js",
102 });
103 highlighterPromiseCache.set(language, promise);
104 return promise;
105}
106
107function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
108 const [copied, setCopied] = useState(false);
109 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
110 const handleCopy = useCallback(() => {
111 if (typeof navigator === "undefined" || navigator.clipboard == null) {
112 return;
113 }
114 void navigator.clipboard
115 .writeText(code)
116 .then(() => {
117 if (copiedTimerRef.current != null) {
118 clearTimeout(copiedTimerRef.current);
119 }
120 setCopied(true);
121 copiedTimerRef.current = setTimeout(() => {
122 setCopied(false);
123 copiedTimerRef.current = null;
124 }, 1200);
125 })
126 .catch(() => undefined);
127 }, [code]);
128
129 useEffect(
130 () => () => {
131 if (copiedTimerRef.current != null) {
132 clearTimeout(copiedTimerRef.current);
133 copiedTimerRef.current = null;
134 }
135 },
136 [],
137 );
138
139 return (
140 <div className="chat-markdown-codeblock">
141 <button
142 type="button"
143 className="chat-markdown-copy-button"
144 onClick={handleCopy}
145 title={copied ? "Copied" : "Copy code"}
146 aria-label={copied ? "Copied" : "Copy code"}
147 >
148 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
149 </button>
150 {children}
151 </div>
152 );
153}
154
155interface SuspenseShikiCodeBlockProps {
156 className: string | undefined;
157 code: string;
158 themeName: DiffThemeName;
159 isStreaming: boolean;
160}
161
162function SuspenseShikiCodeBlock({
163 className,
164 code,
165 themeName,
166 isStreaming,
167}: SuspenseShikiCodeBlockProps) {
168 const language = extractFenceLanguage(className);
169 const cacheKey = createHighlightCacheKey(code, language, themeName);
170 const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
171
172 if (cachedHighlightedHtml != null) {
173 return (
174 <div
175 className="chat-markdown-shiki"
176 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
177 />
178 );
179 }
180
181 const highlighter = use(getHighlighterPromise(language));
182 const highlightedHtml = useMemo(
183 () => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
184 [code, highlighter, language, themeName],
185 );
186
187 useEffect(() => {
188 if (!isStreaming) {
189 highlightedCodeCache.set(
190 cacheKey,
191 highlightedHtml,
192 estimateHighlightedSize(highlightedHtml, code),
193 );
194 }
195 }, [cacheKey, code, highlightedHtml, isStreaming]);
196
197 return (
198 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
199 );
200}
201
202function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
203 const { resolvedTheme } = useTheme();
204 const diffThemeName = resolveDiffThemeName(resolvedTheme);
205 const markdownComponents = useMemo<Components>(
206 () => ({
207 a({ node: _node, href, ...props }) {
208 const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
209 if (!targetPath) {
210 return <a {...props} href={href} target="_blank" rel="noreferrer" />;
211 }
212
213 return (
214 <a
215 {...props}
216 href={href}
217 onClick={(event) => {
218 event.preventDefault();
219 event.stopPropagation();
220 const api = readNativeApi();
221 if (api) {
222 void api.shell.openInEditor(targetPath, preferredTerminalEditor());
223 } else {
224 console.warn("Native API not found. Unable to open file in editor.");
225 }
226 }}
227 />
228 );
229 },
230 pre({ node: _node, children, ...props }) {
231 const codeBlock = extractCodeBlock(children);
232 if (!codeBlock) {
233 return <pre {...props}>{children}</pre>;
234 }
235
236 return (
237 <MarkdownCodeBlock code={codeBlock.code}>
238 <Suspense fallback={<pre {...props}>{children}</pre>}>
239 <SuspenseShikiCodeBlock
240 className={codeBlock.className}
241 code={codeBlock.code}
242 themeName={diffThemeName}
243 isStreaming={isStreaming}
244 />
245 </Suspense>
246 </MarkdownCodeBlock>
247 );
248 },
249 }),
250 [cwd, diffThemeName, isStreaming],
251 );
252
253 return (
254 <div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
255 <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
256 {text}
257 </ReactMarkdown>
258 </div>
259 );
260}
261
262export default memo(ChatMarkdown);