import { Suspense, lazy, memo, startTransition, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { Check, Copy } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useThemeValue } from "@/hooks/useTheme"; import { hasAnsi, parseAnsiSegments, stripAnsi } from "@/lib/ansi"; import { copyTextToClipboard } from "@/lib/clipboard"; import { normalizeCodeLanguage } from "@/lib/code-language"; import { cn } from "@/lib/utils"; interface CodeBlockProps { language?: string; code: string; className?: string; chrome?: "default" | "none"; highlight?: boolean; showLineNumbers?: boolean; wrapLongLines?: boolean; viewportHighlight?: boolean; } interface HighlightedCodeProps { language?: string; code: string; isDark: boolean; chrome: "default" | "none"; showLineNumbers: boolean; wrapLongLines: boolean; viewportHighlight: boolean; } const CODE_FONT_STACK = [ '"JetBrains Mono"', '"SFMono-Regular"', '"SF Mono"', '"Fira Code"', '"Cascadia Code"', '"Source Code Pro"', "Menlo", "Consolas", "monospace", ].join(", "); const ANSI_LANGUAGES = new Set(["ansi", "ansi-output"]); const LazyHighlightedCode = lazy(async () => { const [ { default: SyntaxHighlighter }, { default: oneDark }, { default: oneLight }, { ViewportCodeRows }, ] = await Promise.all([ import("react-syntax-highlighter/dist/esm/prism-async-light"), import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"), import("react-syntax-highlighter/dist/esm/styles/prism/one-light"), import("@/components/ViewportCodeRows"), ]); return { default({ language, code, isDark, chrome, showLineNumbers, wrapLongLines, viewportHighlight, }: HighlightedCodeProps) { const theme = isDark ? oneDark : oneLight; const transparentTheme = chrome === "none" ? { ...theme, 'pre[class*="language-"]': { ...theme['pre[class*="language-"]'], background: "transparent", }, 'code[class*="language-"]': { ...theme['code[class*="language-"]'], background: "transparent", }, } : theme; return ( // during progressive highlighting must not reset horizontal scroll. ...(viewportHighlight ? { overflow: "visible" } : {}), }} codeTagProps={{ style: { background: "transparent", fontFamily: CODE_FONT_STACK, ...(viewportHighlight ? { lineHeight: "inherit" } : {}), }, }} lineNumberStyle={{ minWidth: "2.6em", paddingRight: "1.15rem", color: isDark ? "rgba(212, 212, 216, 0.45)" : "rgba(63, 63, 70, 0.68)", fontFamily: CODE_FONT_STACK, userSelect: "none", }} PreTag="pre" showLineNumbers={showLineNumbers && !viewportHighlight} wrapLongLines={wrapLongLines} renderer={viewportHighlight ? props => : undefined} > {code} ); }, }; }); function renderPlainText(value: string): ReactNode { return value; } function renderAnsiText(value: string): ReactNode { return parseAnsiSegments(value).map((segment, index) => ( {segment.text} )); } function CodeTextBlock({ code, chrome, showLineNumbers, testId, className, renderText = renderPlainText, compact = false, }: { code: string; chrome: "default" | "none"; showLineNumbers: boolean; testId: string; className?: string; renderText?: (value: string) => ReactNode; compact?: boolean; }) { const lines = showLineNumbers ? code.split("\n") : []; return (
      
        {showLineNumbers && compact ? (
          
            {lines.map((_, index) => index + 1).join("\n")}
            {renderText(code)}
          
        ) : showLineNumbers ? (
          lines.map((line, index) => (
            
              
                {index + 1}
              
              {renderText(line || " ")}
              {index < lines.length - 1 ? "\n" : null}
            
          ))
        ) : renderText(code)}
      
    
); } function shouldRenderAnsi(language: string | undefined, code: string): boolean { const normalized = language?.trim().toLowerCase(); return Boolean((normalized && ANSI_LANGUAGES.has(normalized)) || hasAnsi(code)); } export const CodeBlock = memo(function CodeBlock({ language, code, className, chrome = "default", highlight = true, showLineNumbers = false, wrapLongLines = true, viewportHighlight = false, }: CodeBlockProps) { const { t } = useTranslation(); const rootRef = useRef(null); const [copied, setCopied] = useState(false); const [highlightedSource, setHighlightedSource] = useState(null); const renderAnsi = useMemo(() => shouldRenderAnsi(language, code), [language, code]); const plainCode = useMemo(() => renderAnsi ? stripAnsi(code) : code, [renderAnsi, code]); const isDark = useThemeValue() === "dark"; const hasChrome = chrome === "default"; const syntaxLanguage = normalizeCodeLanguage(language); const useViewportHighlight = viewportHighlight && showLineNumbers && !wrapLongLines; // Minified/very large previews must not monopolize the main thread in Prism. // Plain text still contains the entire preview, with normal selection and find. const withinHighlightBudget = useMemo(() => { if (!useViewportHighlight) return true; if (code.length > 100_000) return false; const lines = code.split("\n"); return lines.length <= 2_000 && !lines.some(line => line.length > 2_000); }, [code, useViewportHighlight]); const deferHighlight = highlight && !renderAnsi && useViewportHighlight && withinHighlightBudget && code.length > 8_000; useEffect(() => { if (!deferHighlight) return; // Paint the tab and full plain source first. Color is a progressive enhancement, // not a reason to hold up switching tabs (including an already cached file). let readyToEnhance = false; let frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { readyToEnhance = true; enhance(); }); }); function enhance() { // A tab click may clear a selection before the first frame. Only resume // selection-blocked work here after the initial paint opportunity. if (!readyToEnhance) return; const selection = document.getSelection(); if (rootRef.current && selection && !selection.isCollapsed && selection.rangeCount && selection.getRangeAt(0).intersectsNode(rootRef.current)) return; document.removeEventListener("selectionchange", enhance); startTransition(() => setHighlightedSource(code)); } document.addEventListener("selectionchange", enhance); return () => { cancelAnimationFrame(frame); document.removeEventListener("selectionchange", enhance); }; }, [code, deferHighlight]); const copyLabel = copied ? t("code.copied") : t("code.copyAria"); const onCopy = useCallback(() => { void copyTextToClipboard(plainCode).then((ok) => { if (!ok) return; setCopied(true); setTimeout(() => setCopied(false), 1_500); }); }, [plainCode]); return (
{renderAnsi ? ( ) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? ( } > ) : ( )} {hasChrome ? ( ) : null}
); });