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