import * as React from 'react'; import { useHighlight } from './use-highlight'; import type { Highlighted } from './use-highlight'; export interface CodeProps extends React.HTMLAttributes { code: string; lang?: string; /** Per-line class, e.g. for diff or search highlighting. When set, every line is wrapped in a `[data-line]` span. */ lineClassName?: (lineIndex: number, lineText: string) => string | undefined; } /** Colors from an earlier pass still hold when the new code only appends to the old. */ function usableHighlight(highlighted: Highlighted | null, code: string, lang?: string): Highlighted | null { if (!highlighted || highlighted.lang !== lang) return null; return code.startsWith(highlighted.code) ? highlighted : null; } /** * Low-level syntax-highlighted renderer shared by `CodeBlock` and `MarkdownRenderer`. * Tokens come from the CodeMirror/Lezer grammars and carry `syntax-*` role * classes (components.css) backed by the `--syntax-*` variables, so colors * match the editors and theme switching is pure CSS — no ThemeProvider * required. Renders plain text while highlighting is pending or when the * language is missing/unknown. * * A streaming fence re-renders on every delta while highlighting stays a sample * behind. Dropping the previous tokens each time would strobe the whole block * between colored and plain, so the settled prefix keeps its colors and only * the newly arrived tail waits, uncolored, for the next pass. */ export const Code = React.memo(function Code({ code, lang, lineClassName, ...props }: CodeProps) { const highlighted = useHighlight(code, lang); const usable = usableHighlight(highlighted, code, lang); if (!usable) { if (!lineClassName) return
{code}
; const lines = code.split('\n'); return (
        {lines.map((text, i) => (
          
            
              {text}
            
            {i !== lines.length - 1 && '\n'}
          
        ))}
      
); } const tail = code.slice(usable.code.length); let codeOffset = 0; return (
      
        {usable.tokens.map((line, lineIndex) => {
          const lineOffset = codeOffset;
          let tokenOffset = lineOffset;
          const tokenSpans = line.map(token => {
            const key = tokenOffset;
            tokenOffset += token.content.length;

            return (
              
                {token.content}
              
            );
          });

          codeOffset = tokenOffset + 1;

          return (
            
              {lineClassName ? (
                 token.content).join(''))}
                >
                  {tokenSpans}
                
              ) : (
                {tokenSpans}
              )}
              {lineIndex !== usable.tokens.length - 1 && '\n'}
            
          );
        })}
        {tail}
      
    
); });