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

ChatMarkdown.tsx

574 lines17.6 KB

1import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
2import { CheckIcon, CopyIcon } from "lucide-react";
3import React, {
4 Children,
5 Suspense,
6 type MouseEvent as ReactMouseEvent,
7 isValidElement,
8 use,
9 useCallback,
10 memo,
11 useEffect,
12 useMemo,
13 useRef,
14 useState,
15 type ReactNode,
16} from "react";
17import type { Components } from "react-markdown";
18import ReactMarkdown from "react-markdown";
19import { defaultUrlTransform } from "react-markdown";
20import remarkGfm from "remark-gfm";
21import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
22import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
23import { toastManager } from "./ui/toast";
24import { openInPreferredEditor } from "../editorPreferences";
25import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
26import { fnv1a32 } from "../lib/diffRendering";
27import { LRUCache } from "../lib/lruCache";
28import { useTheme } from "../hooks/useTheme";
29import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
30import { readLocalApi } from "../localApi";
31import { cn } from "../lib/utils";
32​
33class CodeHighlightErrorBoundary extends React.Component<
34 { fallback: ReactNode; children: ReactNode },
35 { hasError: boolean }
36> {
37 constructor(props: { fallback: ReactNode; children: ReactNode }) {
38 super(props);
39 this.state = { hasError: false };
40 }
41​
42 static getDerivedStateFromError() {
43 return { hasError: true };
44 }
45​
46 override render() {
47 if (this.state.hasError) {
48 return this.props.fallback;
49 }
50 return this.props.children;
51 }
53​
54interface ChatMarkdownProps {
55 text: string;
56 cwd: string | undefined;
57 isStreaming?: boolean;
59​
60const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
61const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
62const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
63const highlightedCodeCache = new LRUCache<string>(
64 MAX_HIGHLIGHT_CACHE_ENTRIES,
65 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
66);
67const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
68​
69function extractFenceLanguage(className: string | undefined): string {
70 const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
71 const raw = match?.[1] ?? "text";
72 // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
73 return raw === "gitignore" ? "ini" : raw;
75​
76function nodeToPlainText(node: ReactNode): string {
77 if (typeof node === "string" || typeof node === "number") {
78 return String(node);
79 }
80 if (Array.isArray(node)) {
81 return node.map((child) => nodeToPlainText(child)).join("");
82 }
83 if (isValidElement<{ children?: ReactNode }>(node)) {
84 return nodeToPlainText(node.props.children);
85 }
86 return "";
88​
89function extractCodeBlock(
90 children: ReactNode,
91): { className: string | undefined; code: string } | null {
92 const childNodes = Children.toArray(children);
93 if (childNodes.length !== 1) {
94 return null;
95 }
96​
97 const onlyChild = childNodes[0];
98 if (
99 !isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
100 onlyChild.type !== "code"
101 ) {
102 return null;
103 }
104​
105 return {
106 className: onlyChild.props.className,
107 code: nodeToPlainText(onlyChild.props.children),
108 };
110​
111function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
112 return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
114​
115function estimateHighlightedSize(html: string, code: string): number {
116 return Math.max(html.length * 2, code.length * 3);
118​
119function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
120 const cached = highlighterPromiseCache.get(language);
121 if (cached) return cached;
122​
123 const promise = getSharedHighlighter({
124 themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
125 langs: [language as SupportedLanguages],
126 preferredHighlighter: "shiki-js",
127 }).catch((err) => {
128 highlighterPromiseCache.delete(language);
129 if (language === "text") {
130 // "text" itself failed — Shiki cannot initialize at all, surface the error
131 throw err;
132 }
133 // Language not supported by Shiki — fall back to "text"
134 return getHighlighterPromise("text");
135 });
136 highlighterPromiseCache.set(language, promise);
137 return promise;
139​
140function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
141 const [copied, setCopied] = useState(false);
142 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
143 const handleCopy = useCallback(() => {
144 if (typeof navigator === "undefined" || navigator.clipboard == null) {
145 return;
146 }
147 void navigator.clipboard
148 .writeText(code)
149 .then(() => {
150 if (copiedTimerRef.current != null) {
151 clearTimeout(copiedTimerRef.current);
152 }
153 setCopied(true);
154 copiedTimerRef.current = setTimeout(() => {
155 setCopied(false);
156 copiedTimerRef.current = null;
157 }, 1200);
158 })
159 .catch(() => undefined);
160 }, [code]);
161​
162 useEffect(
163 () => () => {
164 if (copiedTimerRef.current != null) {
165 clearTimeout(copiedTimerRef.current);
166 copiedTimerRef.current = null;
167 }
168 },
169 [],
170 );
171​
172 return (
173 <div className="chat-markdown-codeblock leading-snug">
174 <button
175 type="button"
176 className="chat-markdown-copy-button"
177 onClick={handleCopy}
178 title={copied ? "Copied" : "Copy code"}
179 aria-label={copied ? "Copied" : "Copy code"}
180 >
181 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
182 </button>
183 {children}
184 </div>
185 );
187​
188interface SuspenseShikiCodeBlockProps {
189 className: string | undefined;
190 code: string;
191 themeName: DiffThemeName;
192 isStreaming: boolean;
194​
195function SuspenseShikiCodeBlock({
196 className,
197 code,
198 themeName,
199 isStreaming,
200}: SuspenseShikiCodeBlockProps) {
201 const language = extractFenceLanguage(className);
202 const cacheKey = createHighlightCacheKey(code, language, themeName);
203 const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
204​
205 if (cachedHighlightedHtml != null) {
206 return (
207 <div
208 className="chat-markdown-shiki"
209 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
210 />
211 );
212 }
213​
214 const highlighter = use(getHighlighterPromise(language));
215 const highlightedHtml = useMemo(() => {
216 try {
217 return highlighter.codeToHtml(code, { lang: language, theme: themeName });
218 } catch (error) {
219 // Log highlighting failures for debugging while falling back to plain text
220 console.warn(
221 `Code highlighting failed for language "${language}", falling back to plain text.`,
222 error instanceof Error ? error.message : error,
223 );
224 // If highlighting fails for this language, render as plain text
225 return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
226 }
227 }, [code, highlighter, language, themeName]);
228​
229 useEffect(() => {
230 if (!isStreaming) {
231 highlightedCodeCache.set(
232 cacheKey,
233 highlightedHtml,
234 estimateHighlightedSize(highlightedHtml, code),
235 );
236 }
237 }, [cacheKey, code, highlightedHtml, isStreaming]);
238​
239 return (
240 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
241 );
243​
244interface MarkdownFileLinkProps {
245 href: string;
246 targetPath: string;
247 displayPath: string;
248 filePath: string;
249 label: string;
250 theme: "light" | "dark";
251 className?: string | undefined;
253​
254const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
255const MARKDOWN_FILE_LINK_CLASS_NAME =
256 "chat-markdown-file-link relative top-[2px] max-w-full no-underline";
257const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
258const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
259​
260function pathParentSegments(path: string): string[] {
261 const normalized = path.replaceAll("\\", "/");
262 const segments = normalized.split("/").filter((segment) => segment.length > 0);
263 return segments.slice(0, -1);
265​
266function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<string, string> {
267 const groups = new Map<string, Set<string>>();
268 for (const filePath of filePaths) {
269 const pathSegments = filePath
270 .replaceAll("\\", "/")
271 .split("/")
272 .filter((segment) => segment.length > 0);
273 const basename = pathSegments[pathSegments.length - 1];
274 if (!basename) continue;
275 const group = groups.get(basename) ?? new Set<string>();
276 group.add(filePath);
277 groups.set(basename, group);
278 }
279​
280 const suffixByPath = new Map<string, string>();
281 for (const group of groups.values()) {
282 const uniquePaths = [...group];
283 if (uniquePaths.length < 2) continue;
284​
285 const parentSegmentsByPath = new Map(
286 uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),
287 );
288 const minUniqueDepthByPath = new Map<string, number>();
289​
290 for (const filePath of uniquePaths) {
291 const segments = parentSegmentsByPath.get(filePath) ?? [];
292 let resolvedDepth = segments.length;
293 for (let depth = 1; depth <= segments.length; depth += 1) {
294 const candidate = segments.slice(-depth).join("/");
295 const collision = uniquePaths.some((otherPath) => {
296 if (otherPath === filePath) return false;
297 const otherSegments = parentSegmentsByPath.get(otherPath) ?? [];
298 return otherSegments.slice(-depth).join("/") === candidate;
299 });
300 if (!collision) {
301 resolvedDepth = depth;
302 break;
303 }
304 }
305 minUniqueDepthByPath.set(filePath, resolvedDepth);
306 }
307​
308 for (const filePath of uniquePaths) {
309 const segments = parentSegmentsByPath.get(filePath) ?? [];
310 if (segments.length === 0) continue;
311 const minUniqueDepth = minUniqueDepthByPath.get(filePath) ?? 1;
312 const suffixDepth = Math.min(segments.length, Math.max(minUniqueDepth, 2));
313 suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
314 }
315 }
316​
317 return suffixByPath;
319​
320function extractMarkdownLinkHrefs(text: string): string[] {
321 const hrefs: string[] = [];
322 for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
323 const href = match[1]?.trim();
324 if (!href) continue;
325 hrefs.push(href);
326 }
327 return hrefs;
329​
330function normalizeMarkdownLinkHrefKey(href: string): string {
331 return rewriteMarkdownFileUriHref(href.trim()) ?? href.trim();
333​
334const MarkdownFileLink = memo(function MarkdownFileLink({
335 href,
336 targetPath,
337 displayPath,
338 filePath,
339 label,
340 theme,
341 className,
342}: MarkdownFileLinkProps) {
343 const handleOpen = useCallback(() => {
344 const api = readLocalApi();
345 if (!api) {
346 toastManager.add({
347 type: "error",
348 title: "Open in editor is unavailable",
349 });
350 return;
351 }
352​
353 void openInPreferredEditor(api, targetPath).catch((error) => {
354 toastManager.add({
355 type: "error",
356 title: "Unable to open file",
357 description: error instanceof Error ? error.message : "An error occurred.",
358 });
359 });
360 }, [targetPath]);
361​
362 const handleCopy = useCallback((value: string, title: string) => {
363 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
364 toastManager.add({
365 type: "error",
366 title: `Failed to copy ${title.toLowerCase()}`,
367 description: "Clipboard API unavailable.",
368 });
369 return;
370 }
371​
372 void navigator.clipboard.writeText(value).then(
373 () => {
374 toastManager.add({
375 type: "success",
376 title: `${title} copied`,
377 description: value,
378 });
379 },
380 (error) => {
381 toastManager.add({
382 type: "error",
383 title: `Failed to copy ${title.toLowerCase()}`,
384 description: error instanceof Error ? error.message : "An error occurred.",
385 });
386 },
387 );
388 }, []);
389​
390 const handleContextMenu = useCallback(
391 async (event: ReactMouseEvent<HTMLAnchorElement>) => {
392 event.preventDefault();
393 event.stopPropagation();
394​
395 const api = readLocalApi();
396 if (!api) return;
397​
398 const clicked = await api.contextMenu.show(
399 [
400 { id: "open", label: "Open in editor" },
401 { id: "copy-relative", label: "Copy relative path" },
402 { id: "copy-full", label: "Copy full path" },
403 ] as const,
404 { x: event.clientX, y: event.clientY },
405 );
406​
407 if (clicked === "open") {
408 handleOpen();
409 return;
410 }
411 if (clicked === "copy-relative") {
412 handleCopy(displayPath, "Relative path");
413 return;
414 }
415 if (clicked === "copy-full") {
416 handleCopy(targetPath, "Full path");
417 }
418 },
419 [displayPath, handleCopy, handleOpen, targetPath],
420 );
421​
422 return (
423 <Tooltip>
424 <TooltipTrigger
425 render={
426 <a
427 href={href}
428 className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
429 onClick={(event) => {
430 event.preventDefault();
431 event.stopPropagation();
432 handleOpen();
433 }}
434 onContextMenu={handleContextMenu}
435 >
436 <VscodeEntryIcon
437 pathValue={filePath}
438 kind="file"
439 theme={theme}
440 className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
441 />
442 <span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
443 </a>
444 }
445 />
446 <TooltipPopup
447 side="top"
448 className="max-w-[min(40rem,calc(100vw-2rem))] font-mono text-[11px] leading-tight"
449 >
450 <div className="markdown-file-link-tooltip-scroll overflow-x-auto whitespace-nowrap">
451 {displayPath}
452 </div>
453 </TooltipPopup>
454 </Tooltip>
455 );
456}, areMarkdownFileLinkPropsEqual);
457​
458function areMarkdownFileLinkPropsEqual(
459 previous: Readonly<MarkdownFileLinkProps>,
460 next: Readonly<MarkdownFileLinkProps>,
461): boolean {
462 return (
463 previous.href === next.href &&
464 previous.targetPath === next.targetPath &&
465 previous.displayPath === next.displayPath &&
466 previous.filePath === next.filePath &&
467 previous.label === next.label &&
468 previous.theme === next.theme &&
469 previous.className === next.className
470 );
472​
473function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
474 const { resolvedTheme } = useTheme();
475 const diffThemeName = resolveDiffThemeName(resolvedTheme);
476 const markdownFileLinkMetaByHref = useMemo(() => {
477 const metaByHref = new Map<
478 string,
479 NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
480 >();
481 for (const href of extractMarkdownLinkHrefs(text)) {
482 const normalizedHref = normalizeMarkdownLinkHrefKey(href);
483 if (metaByHref.has(normalizedHref)) continue;
484 const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
485 if (meta) {
486 metaByHref.set(normalizedHref, meta);
487 }
488 }
489 return metaByHref;
490 }, [cwd, text]);
491 const fileLinkParentSuffixByPath = useMemo(() => {
492 const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
493 return buildFileLinkParentSuffixByPath(filePaths);
494 }, [markdownFileLinkMetaByHref]);
495 const markdownUrlTransform = useCallback((href: string) => {
496 return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
497 }, []);
498 const markdownComponents = useMemo<Components>(
499 () => ({
500 a({ node: _node, href, ...props }) {
501 const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
502 const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
503 if (!fileLinkMeta) {
504 return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
505 }
506​
507 const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
508 const labelParts = [fileLinkMeta.basename];
509 if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
510 labelParts.push(parentSuffix);
511 }
512 if (fileLinkMeta.line) {
513 labelParts.push(
514 `L${fileLinkMeta.line}${fileLinkMeta.column ? `:C${fileLinkMeta.column}` : ""}`,
515 );
516 }
517​
518 return (
519 <MarkdownFileLink
520 href={href ?? fileLinkMeta.targetPath}
521 targetPath={fileLinkMeta.targetPath}
522 displayPath={fileLinkMeta.displayPath}
523 filePath={fileLinkMeta.filePath}
524 label={labelParts.join(" · ")}
525 theme={resolvedTheme}
526 className={props.className}
527 />
528 );
529 },
530 pre({ node: _node, children, ...props }) {
531 const codeBlock = extractCodeBlock(children);
532 if (!codeBlock) {
533 return <pre {...props}>{children}</pre>;
534 }
535​
536 return (
537 <MarkdownCodeBlock code={codeBlock.code}>
538 <CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
539 <Suspense fallback={<pre {...props}>{children}</pre>}>
540 <SuspenseShikiCodeBlock
541 className={codeBlock.className}
542 code={codeBlock.code}
543 themeName={diffThemeName}
544 isStreaming={isStreaming}
545 />
546 </Suspense>
547 </CodeHighlightErrorBoundary>
548 </MarkdownCodeBlock>
549 );
550 },
551 }),
552 [
553 diffThemeName,
554 fileLinkParentSuffixByPath,
555 isStreaming,
556 markdownFileLinkMetaByHref,
557 resolvedTheme,
558 ],
559 );
560​
561 return (
562 <div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
563 <ReactMarkdown
564 remarkPlugins={[remarkGfm]}
565 components={markdownComponents}
566 urlTransform={markdownUrlTransform}
567 >
568 {text}
569 </ReactMarkdown>
570 </div>
571 );
573​
574export default memo(ChatMarkdown);