Open History to see the last commit
1import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react";
2import { toHtml } from "hast-util-to-html";
3import React, { use, useEffect, useState, type ReactNode } from "react";
4
5import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
6import { useClientSettings } from "../../hooks/useSettings";
7import type { DiffThemeName } from "../../lib/diffRendering";
8import {
9 createIncrementalHighlightedDocument,
10 highlightCodeToHast,
11} from "../../lib/incrementalHighlighting";
12import { LRUCache } from "../../lib/lruCache";
13import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
14import { cn } from "../../lib/utils";
15import {
16 hasSpecificPierreIconForFileName,
17 syntheticFileNameForLanguageId,
18} from "../../pierre-icons";
19import { Button } from "../ui/button";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { HighlightedCodeLines } from "./HighlightedCodeLines";
22import {
23 createHighlightCacheKey,
24 estimateHighlightedSize,
25 extractFenceLanguage,
26} from "./MarkdownCodeBlock.logic";
27import { reportMarkdownActionFailure } from "./markdownActionFailure";
28import { PierreEntryIcon } from "./PierreEntryIcon";
29
30const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
31const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
32
33const highlightedCodeCache = new LRUCache<string>(
34 MAX_HIGHLIGHT_CACHE_ENTRIES,
35 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
36);
37
38const THREAD_FIND_IGNORE_PROPS = {
39 "data-thread-find-ignore": "",
40} as React.HTMLAttributes<HTMLDivElement>;
41
42export function MarkdownCodeBlockFrame({
43 as: Wrapper = "div",
44 language,
45 fenceTitle,
46 theme,
47 wrapped = true,
48 title,
49 actions,
50 headerProps,
51 children,
52}: {
53 as?: React.ElementType;
54 language: string;
55 fenceTitle: string | null;
56 theme: "light" | "dark";
57 wrapped?: boolean;
58 title?: React.ReactNode;
59 actions?: React.ReactNode;
60 headerProps?: React.HTMLAttributes<HTMLDivElement>;
61 children: React.ReactNode;
62}) {
63 return (
64 <Wrapper
65 dir="ltr"
66 className="chat-markdown-codeblock my-[0.65rem] text-start overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
67 data-language={language}
68 data-wrap={wrapped ? "true" : "false"}
69 >
70 <div
71 {...headerProps}
72 className={cn(
73 "chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",
74 headerProps?.className,
75 )}
76 >
77 {title ?? (
78 <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
79 <MarkdownCodeBlockTitleContent
80 fenceTitle={fenceTitle}
81 language={language}
82 theme={theme}
83 />
84 </span>
85 )}
86 {actions}
87 </div>
88 {children}
89 </Wrapper>
90 );
91}
92
93function MarkdownCodeBlockTitleContent({
94 fenceTitle,
95 language,
96 theme,
97}: {
98 fenceTitle: string | null;
99 language: string;
100 theme: "light" | "dark";
101}) {
102 if (fenceTitle) {
103 return (
104 <>
105 <PierreEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
106 <span className="truncate">{fenceTitle}</span>
107 </>
108 );
109 }
110
111 const fileName = syntheticFileNameForLanguageId(language);
112 if (!hasSpecificPierreIconForFileName(fileName)) {
113 return <span className="truncate">{language}</span>;
114 }
115 return (
116 <Tooltip>
117 <TooltipTrigger
118 render={
119 <span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
120 }
121 >
122 <PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
123 </TooltipTrigger>
124 <TooltipPopup side="top">{language}</TooltipPopup>
125 </Tooltip>
126 );
127}
128
129export function MarkdownCodeBlock({
130 code,
131 language,
132 fenceTitle,
133 theme,
134 onRunShellCommand,
135 isStreaming,
136 viewToggle,
137 canWrap = true,
138 diagram = false,
139 children,
140}: {
141 code: string;
142 language: string;
143 fenceTitle: string | null;
144 theme: "light" | "dark";
145 onRunShellCommand?: ((command: string) => void) | undefined;
146 isStreaming: boolean;
147 viewToggle?: ReactNode;
148 canWrap?: boolean;
149 diagram?: boolean;
150 children: ReactNode;
151}) {
152 const { copyToClipboard, isCopied: copied } = useCopyToClipboard({
153 timeout: 1200,
154 onError: (cause) =>
155 reportMarkdownActionFailure(
156 {
157 operation: "copy-code-block",
158 language,
159 ...(fenceTitle ? { fenceTitle } : {}),
160 },
161 cause,
162 ),
163 });
164 const defaultWrapped = useClientSettings((settings) => settings.wordWrap);
165 const [wrapOverride, setWrapOverride] = useState<boolean | null>(null);
166 const wrapped = wrapOverride ?? defaultWrapped;
167 const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
168 const copyLabel = copied ? "Copied" : "Copy code";
169 const command = code.trim();
170 const canRun =
171 onRunShellCommand !== undefined &&
172 !isStreaming &&
173 /^(?:sh|bash|zsh|fish|shell|powershell|pwsh)$/.test(language) &&
174 code.endsWith("\n") &&
175 command.length > 0 &&
176 !command.endsWith("\\") &&
177 // Control and invisible format characters (bidi overrides, zero-width) can
178 // make the rendered command differ from what the terminal would receive.
179 !/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));
180
181 const handleCopy = () => copyToClipboard(code);
182
183 const copyButton = (
184 <Tooltip>
185 <TooltipTrigger
186 render={
187 <Button
188 type="button"
189 variant="ghost-muted"
190 size="icon-xs"
191 onClick={handleCopy}
192 aria-label={copyLabel}
193 />
194 }
195 >
196 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
197 </TooltipTrigger>
198 <TooltipPopup side="top">{copyLabel}</TooltipPopup>
199 </Tooltip>
200 );
201
202 if (diagram) {
203 return (
204 <div className="my-[0.65rem] border border-transparent" data-language={language}>
205 <div className="flex items-center justify-end gap-0.5 pt-1.5 pr-1.5 select-none">
206 {viewToggle}
207 {copyButton}
208 </div>
209 {children}
210 </div>
211 );
212 }
213
214 return (
215 <MarkdownCodeBlockFrame
216 language={language}
217 fenceTitle={fenceTitle}
218 theme={theme}
219 wrapped={wrapped}
220 headerProps={THREAD_FIND_IGNORE_PROPS}
221 actions={
222 <span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
223 {canWrap ? (
224 <Tooltip>
225 <TooltipTrigger
226 render={
227 <Button
228 type="button"
229 variant={wrapped ? "secondary" : "ghost-muted"}
230 size="icon-xs"
231 aria-pressed={wrapped}
232 onClick={() => setWrapOverride(!wrapped)}
233 aria-label={wrapLabel}
234 />
235 }
236 >
237 <WrapTextIcon className="size-3" />
238 </TooltipTrigger>
239 <TooltipPopup side="top">{wrapLabel}</TooltipPopup>
240 </Tooltip>
241 ) : null}
242 {canRun ? (
243 <Tooltip>
244 <TooltipTrigger
245 render={
246 <Button
247 type="button"
248 variant="ghost-muted"
249 size="icon-xs"
250 onClick={() => onRunShellCommand(command)}
251 aria-label="Run in terminal"
252 />
253 }
254 >
255 <PlayIcon className="size-3" />
256 </TooltipTrigger>
257 <TooltipPopup side="top">Run in terminal</TooltipPopup>
258 </Tooltip>
259 ) : null}
260 {viewToggle}
261 {copyButton}
262 </span>
263 }
264 >
265 {children}
266 </MarkdownCodeBlockFrame>
267 );
268}
269
270interface SuspenseShikiCodeBlockProps {
271 className: string | undefined;
272 code: string;
273 themeName: DiffThemeName;
274 isStreaming: boolean;
275}
276
277export function SuspenseShikiCodeBlock({
278 className,
279 code,
280 themeName,
281 isStreaming,
282}: SuspenseShikiCodeBlockProps) {
283 const [hasStreamed, setHasStreamed] = useState(isStreaming);
284 if (isStreaming && !hasStreamed) setHasStreamed(true);
285 const language = extractFenceLanguage(className);
286 const cacheKey = createHighlightCacheKey(code, language, themeName);
287 // Once lines are mounted individually, keep that renderer when streaming
288 // finishes so switching to cached HTML cannot clear an existing selection.
289 const cachedHighlightedHtml =
290 !isStreaming && !hasStreamed ? highlightedCodeCache.get(cacheKey) : null;
291
292 if (cachedHighlightedHtml != null) {
293 return (
294 <div
295 className="chat-markdown-shiki"
296 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
297 />
298 );
299 }
300
301 return (
302 <UncachedShikiCodeBlock
303 code={code}
304 language={language}
305 themeName={themeName}
306 cacheKey={cacheKey}
307 isStreaming={isStreaming}
308 preserveLines={isStreaming || hasStreamed}
309 />
310 );
311}
312
313interface UncachedShikiCodeBlockProps {
314 code: string;
315 language: string;
316 themeName: DiffThemeName;
317 cacheKey: string;
318 isStreaming: boolean;
319 preserveLines: boolean;
320}
321
322function UncachedShikiCodeBlock({
323 code,
324 language,
325 themeName,
326 cacheKey,
327 isStreaming,
328 preserveLines,
329}: UncachedShikiCodeBlockProps) {
330 const highlighter = use(getSyntaxHighlighterPromise(language));
331 const incrementalHighlight = preserveLines
332 ? createIncrementalHighlightedDocument(highlighter, language, themeName)
333 : null;
334 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- disposes the incremental Shiki highlighter when it is replaced or the block unmounts
335 useEffect(() => () => incrementalHighlight?.dispose(), [incrementalHighlight]);
336 const highlighted = (() => {
337 const result = (() => {
338 try {
339 if (incrementalHighlight) return incrementalHighlight(code);
340 return preserveLines
341 ? highlightCodeToHast(highlighter, code, language, themeName)
342 : highlighter.codeToHtml(code, { lang: language, theme: themeName });
343 } catch (error) {
344 console.warn(
345 `Code highlighting failed for language "${language}", falling back to plain text.`,
346 error instanceof Error ? error.message : error,
347 );
348 return preserveLines
349 ? highlightCodeToHast(highlighter, code, "text", themeName)
350 : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
351 }
352 })();
353 // A finished block is cached for the next mount; a streaming one is still changing.
354 if (!isStreaming) {
355 const highlightedHtml = typeof result === "string" ? result : toHtml(result);
356 highlightedCodeCache.set(
357 cacheKey,
358 highlightedHtml,
359 estimateHighlightedSize(highlightedHtml, cacheKey),
360 );
361 }
362 return result;
363 })();
364
365 return typeof highlighted === "string" ? (
366 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
367 ) : (
368 <div className="chat-markdown-shiki">
369 <HighlightedCodeLines root={highlighted} />
370 </div>
371 );
372}