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

MarkdownCodeBlock.tsx

371 lines10.7 KB

1import { Check, Copy } from "lucide";
2import { PlayIcon, WrapTextIcon } from "lucide-react";
3import { toHtml } from "hast-util-to-html";
4import React, { use, useEffect, useState, type ReactNode } from "react";
5​
6import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
7import { getClientSettings } from "../../hooks/useSettings";
8import type { DiffThemeName } from "../../lib/diffRendering";
9import {
10 createIncrementalHighlightedDocument,
11 highlightCodeToHast,
12} from "../../lib/incrementalHighlighting";
13import { LRUCache } from "../../lib/lruCache";
14import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
15import { cn } from "../../lib/utils";
16import {
17 hasSpecificPierreIconForFileName,
18 syntheticFileNameForLanguageId,
19} from "../../pierre-icons";
20import { MorphIcon } from "../MorphIcon";
21import { Button } from "../ui/button";
22import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23import { HighlightedCodeLines } from "./HighlightedCodeLines";
24import {
25 createHighlightCacheKey,
26 estimateHighlightedSize,
27 extractFenceLanguage,
28} from "./MarkdownCodeBlock.logic";
29import { reportMarkdownActionFailure } from "./markdownActionFailure";
30import { PierreEntryIcon } from "./PierreEntryIcon";
31​
32const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
33const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
34​
35const highlightedCodeCache = new LRUCache<string>(
36 MAX_HIGHLIGHT_CACHE_ENTRIES,
37 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
38);
39​
40const THREAD_FIND_IGNORE_PROPS = {
41 "data-thread-find-ignore": "",
42} as React.HTMLAttributes<HTMLDivElement>;
43​
44export function MarkdownCodeBlockFrame({
45 as: Wrapper = "div",
46 language,
47 fenceTitle,
48 theme,
49 wrapped = true,
50 title,
51 actions,
52 headerProps,
53 children,
54}: {
55 as?: React.ElementType;
56 language: string;
57 fenceTitle: string | null;
58 theme: "light" | "dark";
59 wrapped?: boolean;
60 title?: React.ReactNode;
61 actions?: React.ReactNode;
62 headerProps?: React.HTMLAttributes<HTMLDivElement>;
63 children: React.ReactNode;
64}) {
65 return (
66 <Wrapper
67 dir="ltr"
68 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"
69 data-language={language}
70 data-wrap={wrapped ? "true" : "false"}
71 >
72 <div
73 {...headerProps}
74 className={cn(
75 "chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",
76 headerProps?.className,
77 )}
78 >
79 {title ?? (
80 <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
81 <MarkdownCodeBlockTitleContent
82 fenceTitle={fenceTitle}
83 language={language}
84 theme={theme}
85 />
86 </span>
87 )}
88 {actions}
89 </div>
90 {children}
91 </Wrapper>
92 );
94​
95function MarkdownCodeBlockTitleContent({
96 fenceTitle,
97 language,
98 theme,
99}: {
100 fenceTitle: string | null;
101 language: string;
102 theme: "light" | "dark";
103}) {
104 if (fenceTitle) {
105 return (
106 <>
107 <PierreEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
108 <span className="truncate">{fenceTitle}</span>
109 </>
110 );
111 }
112​
113 const fileName = syntheticFileNameForLanguageId(language);
114 if (!hasSpecificPierreIconForFileName(fileName)) {
115 return <span className="truncate">{language}</span>;
116 }
117 return (
118 <Tooltip>
119 <TooltipTrigger
120 render={
121 <span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
122 }
123 >
124 <PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
125 </TooltipTrigger>
126 <TooltipPopup side="top">{language}</TooltipPopup>
127 </Tooltip>
128 );
130​
131export function MarkdownCodeBlock({
132 code,
133 language,
134 fenceTitle,
135 theme,
136 onRunShellCommand,
137 isStreaming,
138 viewToggle,
139 canWrap = true,
140 diagram = false,
141 children,
142}: {
143 code: string;
144 language: string;
145 fenceTitle: string | null;
146 theme: "light" | "dark";
147 onRunShellCommand?: ((command: string) => void) | undefined;
148 isStreaming: boolean;
149 viewToggle?: ReactNode;
150 canWrap?: boolean;
151 diagram?: boolean;
152 children: ReactNode;
153}) {
154 const { copyToClipboard, isCopied: copied } = useCopyToClipboard({
155 timeout: 1200,
156 onError: (cause) =>
157 reportMarkdownActionFailure(
158 {
159 operation: "copy-code-block",
160 language,
161 ...(fenceTitle ? { fenceTitle } : {}),
162 },
163 cause,
164 ),
165 });
166 const [wrapped, setWrapped] = useState(() => getClientSettings().wordWrap);
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 <MorphIcon className="size-3" icon={copied ? Check : Copy} />
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={() => setWrapped((value) => !value)}
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 );
269​
270interface SuspenseShikiCodeBlockProps {
271 className: string | undefined;
272 code: string;
273 themeName: DiffThemeName;
274 isStreaming: boolean;
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 );
312​
313interface UncachedShikiCodeBlockProps {
314 code: string;
315 language: string;
316 themeName: DiffThemeName;
317 cacheKey: string;
318 isStreaming: boolean;
319 preserveLines: boolean;
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 useEffect(() => () => incrementalHighlight?.dispose(), [incrementalHighlight]);
335 const highlighted = (() => {
336 const result = (() => {
337 try {
338 if (incrementalHighlight) return incrementalHighlight(code);
339 return preserveLines
340 ? highlightCodeToHast(highlighter, code, language, themeName)
341 : highlighter.codeToHtml(code, { lang: language, theme: themeName });
342 } catch (error) {
343 console.warn(
344 `Code highlighting failed for language "${language}", falling back to plain text.`,
345 error instanceof Error ? error.message : error,
346 );
347 return preserveLines
348 ? highlightCodeToHast(highlighter, code, "text", themeName)
349 : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
350 }
351 })();
352 // A finished block is cached for the next mount; a streaming one is still changing.
353 if (!isStreaming) {
354 const highlightedHtml = typeof result === "string" ? result : toHtml(result);
355 highlightedCodeCache.set(
356 cacheKey,
357 highlightedHtml,
358 estimateHighlightedSize(highlightedHtml, code),
359 );
360 }
361 return result;
362 })();
363​
364 return typeof highlighted === "string" ? (
365 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
366 ) : (
367 <div className="chat-markdown-shiki">
368 <HighlightedCodeLines root={highlighted} />
369 </div>
370 );