The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { T, useGT } from "gt-react"; |
| 2 | import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; |
| 3 | import { toHtml } from "hast-util-to-html"; |
| 4 | import React, { use, useEffect, useState, type ReactNode } from "react"; |
| 5 | |
| 6 | import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; |
| 7 | import { useClientSettings } from "../../hooks/useSettings"; |
| 8 | import type { DiffThemeName } from "../../lib/diffRendering"; |
| 9 | import { |
| 10 | createIncrementalHighlightedDocument, |
| 11 | highlightCodeToHast, |
| 12 | } from "../../lib/incrementalHighlighting"; |
| 13 | import { LRUCache } from "../../lib/lruCache"; |
| 14 | import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting"; |
| 15 | import { cn } from "../../lib/utils"; |
| 16 | import { |
| 17 | hasSpecificPierreIconForFileName, |
| 18 | syntheticFileNameForLanguageId, |
| 19 | } from "../../pierre-icons"; |
| 20 | import { Button } from "../ui/button"; |
| 21 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 22 | import { HighlightedCodeLines } from "./HighlightedCodeLines"; |
| 23 | import { |
| 24 | createHighlightCacheKey, |
| 25 | estimateHighlightedSize, |
| 26 | extractFenceLanguage, |
| 27 | } from "./MarkdownCodeBlock.logic"; |
| 28 | import { reportMarkdownActionFailure } from "./markdownActionFailure"; |
| 29 | import { PierreEntryIcon } from "./PierreEntryIcon"; |
| 30 | |
| 31 | const MAX_HIGHLIGHT_CACHE_ENTRIES = 500; |
| 32 | const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024; |
| 33 | |
| 34 | const highlightedCodeCache = new LRUCache<string>( |
| 35 | MAX_HIGHLIGHT_CACHE_ENTRIES, |
| 36 | MAX_HIGHLIGHT_CACHE_MEMORY_BYTES, |
| 37 | ); |
| 38 | |
| 39 | const THREAD_FIND_IGNORE_PROPS = { |
| 40 | "data-thread-find-ignore": "", |
| 41 | } as React.HTMLAttributes<HTMLDivElement>; |
| 42 | |
| 43 | export 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 | ); |
| 92 | } |
| 93 | |
| 94 | function 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 | <Tooltip> |
| 119 | <TooltipTrigger |
| 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 | </TooltipTrigger> |
| 129 | <TooltipPopup side="top">{language}</TooltipPopup> |
| 130 | </Tooltip> |
| 131 | ); |
| 132 | } |
| 133 | |
| 134 | export function MarkdownCodeBlock({ |
| 135 | code, |
| 136 | language, |
| 137 | fenceTitle, |
| 138 | theme, |
| 139 | onRunShellCommand, |
| 140 | isStreaming, |
| 141 | viewToggle, |
| 142 | canWrap = true, |
| 143 | diagram = false, |
| 144 | children, |
| 145 | }: { |
| 146 | code: string; |
| 147 | language: string; |
| 148 | fenceTitle: string | null; |
| 149 | theme: "light" | "dark"; |
| 150 | onRunShellCommand?: ((command: string) => void) | undefined; |
| 151 | isStreaming: boolean; |
| 152 | viewToggle?: ReactNode; |
| 153 | canWrap?: boolean; |
| 154 | diagram?: boolean; |
| 155 | children: ReactNode; |
| 156 | }) { |
| 157 | const gt = useGT(); |
| 158 | const { copyToClipboard, isCopied: copied } = useCopyToClipboard({ |
| 159 | timeout: 1200, |
| 160 | onError: (cause) => |
| 161 | reportMarkdownActionFailure( |
| 162 | { |
| 163 | operation: "copy-code-block", |
| 164 | language, |
| 165 | ...(fenceTitle ? { fenceTitle } : {}), |
| 166 | }, |
| 167 | cause, |
| 168 | ), |
| 169 | }); |
| 170 | const defaultWrapped = useClientSettings((settings) => settings.wordWrap); |
| 171 | const [wrapOverride, setWrapOverride] = useState<boolean | null>(null); |
| 172 | const wrapped = wrapOverride ?? defaultWrapped; |
| 173 | const wrapLabel = wrapped ? gt("Disable line wrap") : gt("Wrap lines"); |
| 174 | const copyLabel = copied ? gt("Copied") : gt("Copy code"); |
| 175 | const command = code.trim(); |
| 176 | const canRun = |
| 177 | onRunShellCommand !== undefined && |
| 178 | !isStreaming && |
| 179 | /^(?:sh|bash|zsh|fish|shell|powershell|pwsh)$/.test(language) && |
| 180 | code.endsWith("\n") && |
| 181 | command.length > 0 && |
| 182 | !command.endsWith("\\") && |
| 183 | // Control and invisible format characters (bidi overrides, zero-width) can |
| 184 | // make the rendered command differ from what the terminal would receive. |
| 185 | !/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1)); |
| 186 | |
| 187 | const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); |
| 188 | |
| 189 | const copyButton = ( |
| 190 | <Tooltip> |
| 191 | <TooltipTrigger |
| 192 | render={ |
| 193 | <Button |
| 194 | type="button" |
| 195 | variant="ghost-muted" |
| 196 | size="icon-xs" |
| 197 | onClick={handleCopy} |
| 198 | aria-label={copyLabel} |
| 199 | /> |
| 200 | } |
| 201 | > |
| 202 | {copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />} |
| 203 | </TooltipTrigger> |
| 204 | <TooltipPopup side="top">{copyLabel}</TooltipPopup> |
| 205 | </Tooltip> |
| 206 | ); |
| 207 | |
| 208 | if (diagram) { |
| 209 | return ( |
| 210 | <div className="my-[0.65rem] border border-transparent" data-language={language}> |
| 211 | <div className="flex items-center justify-end gap-0.5 pt-1.5 pr-1.5 select-none"> |
| 212 | {viewToggle} |
| 213 | {copyButton} |
| 214 | </div> |
| 215 | {children} |
| 216 | </div> |
| 217 | ); |
| 218 | } |
| 219 | |
| 220 | return ( |
| 221 | <MarkdownCodeBlockFrame |
| 222 | language={language} |
| 223 | fenceTitle={fenceTitle} |
| 224 | theme={theme} |
| 225 | wrapped={wrapped} |
| 226 | headerProps={THREAD_FIND_IGNORE_PROPS} |
| 227 | actions={ |
| 228 | <span |
| 229 | className="flex items-center gap-0.5" |
| 230 | role="toolbar" |
| 231 | aria-label={gt("Code block actions")} |
| 232 | > |
| 233 | {canWrap ? ( |
| 234 | <Tooltip> |
| 235 | <TooltipTrigger |
| 236 | render={ |
| 237 | <Button |
| 238 | type="button" |
| 239 | variant={wrapped ? "secondary" : "ghost-muted"} |
| 240 | size="icon-xs" |
| 241 | aria-pressed={wrapped} |
| 242 | onClick={() => setWrapOverride(!wrapped)} |
| 243 | aria-label={wrapLabel} |
| 244 | /> |
| 245 | } |
| 246 | > |
| 247 | <WrapTextIcon className="size-3" /> |
| 248 | </TooltipTrigger> |
| 249 | <TooltipPopup side="top">{wrapLabel}</TooltipPopup> |
| 250 | </Tooltip> |
| 251 | ) : null} |
| 252 | {canRun ? ( |
| 253 | <Tooltip> |
| 254 | <TooltipTrigger |
| 255 | render={ |
| 256 | <Button |
| 257 | type="button" |
| 258 | variant="ghost-muted" |
| 259 | size="icon-xs" |
| 260 | onClick={() => onRunShellCommand(command)} |
| 261 | aria-label={gt("Run in terminal")} |
| 262 | /> |
| 263 | } |
| 264 | > |
| 265 | <PlayIcon className="size-3" /> |
| 266 | </TooltipTrigger> |
| 267 | <TooltipPopup side="top"> |
| 268 | <T>Run in terminal</T> |
| 269 | </TooltipPopup> |
| 270 | </Tooltip> |
| 271 | ) : null} |
| 272 | {viewToggle} |
| 273 | {copyButton} |
| 274 | </span> |
| 275 | } |
| 276 | > |
| 277 | {children} |
| 278 | </MarkdownCodeBlockFrame> |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | interface SuspenseShikiCodeBlockProps { |
| 283 | className: string | undefined; |
| 284 | code: string; |
| 285 | themeName: DiffThemeName; |
| 286 | isStreaming: boolean; |
| 287 | } |
| 288 | |
| 289 | export function SuspenseShikiCodeBlock({ |
| 290 | className, |
| 291 | code, |
| 292 | themeName, |
| 293 | isStreaming, |
| 294 | }: SuspenseShikiCodeBlockProps) { |
| 295 | const [hasStreamed, setHasStreamed] = useState(isStreaming); |
| 296 | if (isStreaming && !hasStreamed) setHasStreamed(true); |
| 297 | const language = extractFenceLanguage(className); |
| 298 | const cacheKey = createHighlightCacheKey(code, language, themeName); |
| 299 | // Once lines are mounted individually, keep that renderer when streaming |
| 300 | // finishes so switching to cached HTML cannot clear an existing selection. |
| 301 | const cachedHighlightedHtml = |
| 302 | !isStreaming && !hasStreamed ? highlightedCodeCache.get(cacheKey) : null; |
| 303 | |
| 304 | if (cachedHighlightedHtml != null) { |
| 305 | return ( |
| 306 | <div |
| 307 | className="chat-markdown-shiki" |
| 308 | dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }} |
| 309 | /> |
| 310 | ); |
| 311 | } |
| 312 | |
| 313 | return ( |
| 314 | <UncachedShikiCodeBlock |
| 315 | code={code} |
| 316 | language={language} |
| 317 | themeName={themeName} |
| 318 | cacheKey={cacheKey} |
| 319 | isStreaming={isStreaming} |
| 320 | preserveLines={isStreaming || hasStreamed} |
| 321 | /> |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | interface UncachedShikiCodeBlockProps { |
| 326 | code: string; |
| 327 | language: string; |
| 328 | themeName: DiffThemeName; |
| 329 | cacheKey: string; |
| 330 | isStreaming: boolean; |
| 331 | preserveLines: boolean; |
| 332 | } |
| 333 | |
| 334 | function UncachedShikiCodeBlock({ |
| 335 | code, |
| 336 | language, |
| 337 | themeName, |
| 338 | cacheKey, |
| 339 | isStreaming, |
| 340 | preserveLines, |
| 341 | }: UncachedShikiCodeBlockProps) { |
| 342 | const highlighter = use(getSyntaxHighlighterPromise(language)); |
| 343 | const incrementalHighlight = preserveLines |
| 344 | ? createIncrementalHighlightedDocument(highlighter, language, themeName) |
| 345 | : null; |
| 346 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- disposes the incremental Shiki highlighter when it is replaced or the block unmounts |
| 347 | useEffect(() => () => incrementalHighlight?.dispose(), [incrementalHighlight]); |
| 348 | const highlighted = (() => { |
| 349 | const result = (() => { |
| 350 | try { |
| 351 | if (incrementalHighlight) return incrementalHighlight(code); |
| 352 | return preserveLines |
| 353 | ? highlightCodeToHast(highlighter, code, language, themeName) |
| 354 | : highlighter.codeToHtml(code, { lang: language, theme: themeName }); |
| 355 | } catch (error) { |
| 356 | console.warn( |
| 357 | `Code highlighting failed for language "${language}", falling back to plain text.`, |
| 358 | error instanceof Error ? error.message : error, |
| 359 | ); |
| 360 | return preserveLines |
| 361 | ? highlightCodeToHast(highlighter, code, "text", themeName) |
| 362 | : highlighter.codeToHtml(code, { lang: "text", theme: themeName }); |
| 363 | } |
| 364 | })(); |
| 365 | // A finished block is cached for the next mount; a streaming one is still changing. |
| 366 | if (!isStreaming) { |
| 367 | const highlightedHtml = typeof result === "string" ? result : toHtml(result); |
| 368 | highlightedCodeCache.set( |
| 369 | cacheKey, |
| 370 | highlightedHtml, |
| 371 | estimateHighlightedSize(highlightedHtml, cacheKey), |
| 372 | ); |
| 373 | } |
| 374 | return result; |
| 375 | })(); |
| 376 | |
| 377 | return typeof highlighted === "string" ? ( |
| 378 | <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} /> |
| 379 | ) : ( |
| 380 | <div className="chat-markdown-shiki"> |
| 381 | <HighlightedCodeLines root={highlighted} /> |
| 382 | </div> |
| 383 | ); |
| 384 | } |