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

MarkdownCodeBlock.tsx

374 lines10.8 KB

1import { useGT } from "gt-react";
2import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } 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 { useClientSettings } 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 { Button } from "../ui/button";
21import { SharedTooltipTrigger } from "../ui/shared-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] text-start 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 const gt = useGT();
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 <SharedTooltipTrigger
119 label={language}
120 render={
121 <span
122 className="inline-flex shrink-0 rounded-sm"
123 aria-label={gt("Language: {language}", { language })}
124 />
125 }
126 >
127 <PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
128 </SharedTooltipTrigger>
129 );
131​
132export function MarkdownCodeBlock({
133 code,
134 language,
135 fenceTitle,
136 theme,
137 onRunShellCommand,
138 isStreaming,
139 viewToggle,
140 canWrap = true,
141 diagram = false,
142 children,
143}: {
144 code: string;
145 language: string;
146 fenceTitle: string | null;
147 theme: "light" | "dark";
148 onRunShellCommand?: ((command: string) => void) | undefined;
149 isStreaming: boolean;
150 viewToggle?: ReactNode;
151 canWrap?: boolean;
152 diagram?: boolean;
153 children: ReactNode;
154}) {
155 const gt = useGT();
156 const { copyToClipboard, isCopied: copied } = useCopyToClipboard({
157 timeout: 1200,
158 onError: (cause) =>
159 reportMarkdownActionFailure(
160 {
161 operation: "copy-code-block",
162 language,
163 ...(fenceTitle ? { fenceTitle } : {}),
164 },
165 cause,
166 ),
167 });
168 const defaultWrapped = useClientSettings((settings) => settings.wordWrap);
169 const [wrapOverride, setWrapOverride] = useState<boolean | null>(null);
170 const wrapped = wrapOverride ?? defaultWrapped;
171 const wrapLabel = wrapped ? gt("Disable line wrap") : gt("Wrap lines");
172 const copyLabel = copied ? gt("Copied") : gt("Copy code");
173 const command = code.trim();
174 const canRun =
175 onRunShellCommand !== undefined &&
176 !isStreaming &&
177 /^(?:sh|bash|zsh|fish|shell|powershell|pwsh)$/.test(language) &&
178 code.endsWith("\n") &&
179 command.length > 0 &&
180 !command.endsWith("\\") &&
181 // Control and invisible format characters (bidi overrides, zero-width) can
182 // make the rendered command differ from what the terminal would receive.
183 !/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));
184​
185 const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code);
186​
187 const copyButton = (
188 <SharedTooltipTrigger
189 label={copyLabel}
190 render={
191 <Button
192 type="button"
193 variant="ghost-muted"
194 size="icon-xs"
195 onClick={handleCopy}
196 aria-label={copyLabel}
197 />
198 }
199 >
200 {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
201 </SharedTooltipTrigger>
202 );
203​
204 if (diagram) {
205 return (
206 <div className="my-[0.65rem] border border-transparent" data-language={language}>
207 <div className="flex items-center justify-end gap-0.5 pt-1.5 pr-1.5 select-none">
208 {viewToggle}
209 {copyButton}
210 </div>
211 {children}
212 </div>
213 );
214 }
215​
216 return (
217 <MarkdownCodeBlockFrame
218 language={language}
219 fenceTitle={fenceTitle}
220 theme={theme}
221 wrapped={wrapped}
222 headerProps={THREAD_FIND_IGNORE_PROPS}
223 actions={
224 <span
225 className="flex items-center gap-0.5"
226 role="toolbar"
227 aria-label={gt("Code block actions")}
228 >
229 {canWrap ? (
230 <SharedTooltipTrigger
231 label={wrapLabel}
232 render={
233 <Button
234 type="button"
235 variant={wrapped ? "secondary" : "ghost-muted"}
236 size="icon-xs"
237 aria-pressed={wrapped}
238 onClick={() => setWrapOverride(!wrapped)}
239 aria-label={wrapLabel}
240 />
241 }
242 >
243 <WrapTextIcon className="size-3" />
244 </SharedTooltipTrigger>
245 ) : null}
246 {canRun ? (
247 <SharedTooltipTrigger
248 label={gt("Run in terminal")}
249 render={
250 <Button
251 type="button"
252 variant="ghost-muted"
253 size="icon-xs"
254 onClick={() => onRunShellCommand(command)}
255 aria-label={gt("Run in terminal")}
256 />
257 }
258 >
259 <PlayIcon className="size-3" />
260 </SharedTooltipTrigger>
261 ) : null}
262 {viewToggle}
263 {copyButton}
264 </span>
265 }
266 >
267 {children}
268 </MarkdownCodeBlockFrame>
269 );
271​
272interface SuspenseShikiCodeBlockProps {
273 className: string | undefined;
274 code: string;
275 themeName: DiffThemeName;
276 isStreaming: boolean;
278​
279export function SuspenseShikiCodeBlock({
280 className,
281 code,
282 themeName,
283 isStreaming,
284}: SuspenseShikiCodeBlockProps) {
285 const [hasStreamed, setHasStreamed] = useState(isStreaming);
286 if (isStreaming && !hasStreamed) setHasStreamed(true);
287 const language = extractFenceLanguage(className);
288 const cacheKey = createHighlightCacheKey(code, language, themeName);
289 // Once lines are mounted individually, keep that renderer when streaming
290 // finishes so switching to cached HTML cannot clear an existing selection.
291 const cachedHighlightedHtml =
292 !isStreaming && !hasStreamed ? highlightedCodeCache.get(cacheKey) : null;
293​
294 if (cachedHighlightedHtml != null) {
295 return (
296 <div
297 className="chat-markdown-shiki"
298 dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
299 />
300 );
301 }
302​
303 return (
304 <UncachedShikiCodeBlock
305 code={code}
306 language={language}
307 themeName={themeName}
308 cacheKey={cacheKey}
309 isStreaming={isStreaming}
310 preserveLines={isStreaming || hasStreamed}
311 />
312 );
314​
315interface UncachedShikiCodeBlockProps {
316 code: string;
317 language: string;
318 themeName: DiffThemeName;
319 cacheKey: string;
320 isStreaming: boolean;
321 preserveLines: boolean;
323​
324function UncachedShikiCodeBlock({
325 code,
326 language,
327 themeName,
328 cacheKey,
329 isStreaming,
330 preserveLines,
331}: UncachedShikiCodeBlockProps) {
332 const highlighter = use(getSyntaxHighlighterPromise(language));
333 const incrementalHighlight = preserveLines
334 ? createIncrementalHighlightedDocument(highlighter, language, themeName)
335 : null;
336 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- disposes the incremental Shiki highlighter when it is replaced or the block unmounts
337 useEffect(() => () => incrementalHighlight?.dispose(), [incrementalHighlight]);
338 const highlighted = (() => {
339 const result = (() => {
340 try {
341 if (incrementalHighlight) return incrementalHighlight(code);
342 return preserveLines
343 ? highlightCodeToHast(highlighter, code, language, themeName)
344 : highlighter.codeToHtml(code, { lang: language, theme: themeName });
345 } catch (error) {
346 console.warn(
347 `Code highlighting failed for language "${language}", falling back to plain text.`,
348 error instanceof Error ? error.message : error,
349 );
350 return preserveLines
351 ? highlightCodeToHast(highlighter, code, "text", themeName)
352 : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
353 }
354 })();
355 // A finished block is cached for the next mount; a streaming one is still changing.
356 if (!isStreaming) {
357 const highlightedHtml = typeof result === "string" ? result : toHtml(result);
358 highlightedCodeCache.set(
359 cacheKey,
360 highlightedHtml,
361 estimateHighlightedSize(highlightedHtml, cacheKey),
362 );
363 }
364 return result;
365 })();
366​
367 return typeof highlighted === "string" ? (
368 <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
369 ) : (
370 <div className="chat-markdown-shiki">
371 <HighlightedCodeLines root={highlighted} />
372 </div>
373 );