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

MarkdownCodeBlock.tsx

395 lines11.2 KB

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