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