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