Skip to content

Your lightweight open-source personal agent.

8.9 KB
Raw Blame
import { Component, 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 { discardCodeHighlight } from "@/lib/code-highlight-cache";
import { cn } from "@/lib/utils";

interface CodeBlockProps {
  language?: string;
  code: string;
  className?: string;
  chrome?: "default" | "none";
  highlight?: boolean;
  ansi?: boolean;
  showLineNumbers?: boolean;
  wrapLongLines?: boolean;
  viewportHighlight?: boolean;
}

const ANSI_LANGUAGES = new Set(["ansi", "ansi-output"]);

const LazyHighlightedCode = lazy(async () => {
  const { HighlightedCode } = await import("./HighlightedCode");
  return { default: HighlightedCode };
});

class CodeHighlightBoundary extends Component<{
  code: string;
  language: string;
  fallback: ReactNode;
  children: ReactNode;
}, { failed: boolean }> {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  componentDidCatch(error: Error) {
    discardCodeHighlight(this.props.code, this.props.language);
    console.warn("Code highlighting failed.", error);
  }

  componentDidUpdate(previous: Readonly<{ code: string; language: string }>) {
    if (this.state.failed && (previous.code !== this.props.code || previous.language !== this.props.language)) {
      this.setState({ failed: false });
    }
  }

  render() {
    return this.state.failed ? this.props.fallback : this.props.children;
  }
}

function renderPlainText(value: string): ReactNode {
  return value;
}

function renderAnsiText(value: string, theme: "light" | "dark"): ReactNode {
  return parseAnsiSegments(value, theme).map((segment, index) => (
    <span key={index} style={segment.style}>
      {segment.text}
    </span>
  ));
}

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 (
    <pre
      className={cn(
        "m-0 bg-transparent font-mono text-code text-foreground/90",
        compact ? "overflow-visible" : "overflow-x-auto",
        showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",
        chrome === "default"
          ? "py-4 pl-5 pr-14"
          : compact ? "py-3 pl-2 pr-4" : "p-3",
        className,
      )}
      data-testid={testId}
    >
      <code className="text-inherit">
        {showLineNumbers && compact ? (
          <span className="flex min-w-max">
            <span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
              style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")}</span>
            <span>{renderText(code)}</span>
          </span>
        ) : showLineNumbers ? (
          lines.map((line, index) => (
            <span key={index} className="flex min-w-max">
              <span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground">
                {index + 1}
              </span>
              <span className="whitespace-pre">{renderText(line || " ")}</span>
              {index < lines.length - 1 ? "\n" : null}
            </span>
          ))
        ) : renderText(code)}
      </code>
    </pre>
  );
}

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,
  ansi = true,
  showLineNumbers = false,
  wrapLongLines = true,
  viewportHighlight = false,
}: CodeBlockProps) {
  const { t } = useTranslation();
  const rootRef = useRef<HTMLDivElement>(null);
  const [copied, setCopied] = useState(false);
  const [highlightedSource, setHighlightedSource] = useState<string | null>(null);
  const renderAnsi = useMemo(() => ansi && shouldRenderAnsi(language, code), [ansi, 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 during highlighting.
  // 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 plainBlock = <CodeTextBlock code={code} chrome={chrome} showLineNumbers={showLineNumbers}
    testId="plain-code-fallback" compact={useViewportHighlight} />;

  const onCopy = useCallback(() => {
    void copyTextToClipboard(plainCode).then((ok) => {
      if (!ok) return;
      setCopied(true);
      setTimeout(() => setCopied(false), 1_500);
    });
  }, [plainCode]);

  return (
    <div
      ref={rootRef}
      className={cn(
        "not-prose relative code-content font-mono text-code",
        useViewportHighlight ? "overflow-visible" : "overflow-hidden",
        hasChrome && "rounded-floating bg-secondary/70",
        className,
      )}
      data-language={language || t("code.fallbackLanguage")}
    >
      {renderAnsi ? (
        <CodeTextBlock
          code={code}
          chrome={chrome}
          showLineNumbers={showLineNumbers}
          testId="ansi-code"
          renderText={(value) => renderAnsiText(value, isDark ? "dark" : "light")}
          compact={useViewportHighlight}
        />
      ) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
        <CodeHighlightBoundary code={code} language={syntaxLanguage} fallback={plainBlock}>
          <Suspense fallback={plainBlock}>
            <LazyHighlightedCode
              language={syntaxLanguage}
              code={code}
              chrome={chrome}
              showLineNumbers={showLineNumbers}
              wrapLongLines={wrapLongLines}
              viewportHighlight={useViewportHighlight}
            />
          </Suspense>
        </CodeHighlightBoundary>
      ) : plainBlock}
      {hasChrome ? (
        <button
          type="button"
          onClick={onCopy}
          className={cn(
            "absolute right-2.5 top-2.5 z-10 inline-flex h-8 w-8 items-center justify-center rounded-full",
            "text-muted-foreground transition-colors hover:text-foreground",
            "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
          )}
          aria-label={copyLabel}
          title={copyLabel}
        >
          {copied ? (
            <Check className="h-4 w-4" aria-hidden />
          ) : (
            <Copy className="h-4 w-4" aria-hidden />
          )}
        </button>
      ) : null}
    </div>
  );
});