import classNames from 'classnames'; import Prism from 'prismjs'; import * as css from '../../styles/CustomHtml.css'; // Side-effect import: registers every prism language grammar and the token colors // used by the classes below (`token ` inside a `code` element). import './ReactPrism'; export type PrismSegment = { type?: string; text: string; }; export type PrismLine = PrismSegment[]; /** * Tokenizes `text` with the prism grammar of `language` and splits the result into * lines. Tokens spanning multiple lines (block comments, multiline strings) are split * so every line keeps the token type of its segments, which keeps the colors correct * when lines are rendered one row at a time. */ export function tokenizeToLines(text: string, language?: string): PrismLine[] { const grammar = language ? Prism.languages[language] : undefined; if (!grammar) return text.split('\n').map((line) => [{ text: line }]); const lines: PrismLine[] = [[]]; const append = (type: string | undefined, value: string) => { const parts = value.split('\n'); parts.forEach((part, index) => { if (index > 0) lines.push([]); if (part) lines[lines.length - 1].push({ type, text: part }); }); }; const walk = (stream: Prism.TokenStream, type?: string) => { if (typeof stream === 'string') { append(type, stream); return; } if (Array.isArray(stream)) { stream.forEach((child) => walk(child, type)); return; } walk(stream.content, stream.type); }; Prism.tokenize(text, grammar).forEach((token) => walk(token)); return lines; } export default function PrismCode({ text, language, showLineNumbers, }: { text: string; language?: string; showLineNumbers: boolean; }) { const lines = tokenizeToLines(text, language); return ( {lines.map((line, lineIndex) => ( {showLineNumbers && {lineIndex + 1}} {line.map((segment, segmentIndex) => segment.type ? ( {segment.text} ) : ( segment.text ), )} ))} ); }