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

ChatMarkdown.tsx

308 lines9.2 KB

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