import { DocumentBlockCode, JSONDocument } from '@gitbook/api'; import { ContentRefContext } from '@/lib/references'; import { ClassValue, tcls } from '@/lib/tailwind'; import { CopyCodeButton } from './CopyCodeButton'; import { colorToCSSVar, highlight, HighlightLine, HighlightToken } from './highlight'; import { BlockProps } from '../Block'; import { Inline } from '../Inline'; import './theme.css'; /** * Render an entire code-block. The syntax highlighting is done server-side. */ export async function CodeBlock(props: BlockProps) { const { block, document, style, context } = props; const lines = await highlight(block); const id = block.key!; const withLineNumbers = !!block.data.lineNumbers && block.nodes.length > 1; const withWrap = block.data.overflow === 'wrap'; const title = block.data.title; const fullWidth = block.data.fullWidth; const fullWidthStyle = fullWidth ? 'max-w-4xl' : 'max-w-3xl'; const titleRounding = title ? ['rounded-md', 'rounded-ss-none'] : ['rounded-md']; return (
{title ? (
{title}
) : null}
                
                    {lines.map((line, index) => (
                        
                    ))}
                
            
); } function CodeHighlightLine(props: { block: DocumentBlockCode; document: JSONDocument; line: HighlightLine; lineIndex: number; isLast: boolean; withLineNumbers: boolean; withWrap: boolean; context: ContentRefContext; }) { const { block, document, line, isLast, withLineNumbers, context } = props; return ( *]:mt-1', //last child '[&.highlighted:last-child]:rounded-b-md', '[&.highlighted:last-child>*]:mb-1', //is only child, dont hover effect line '[&:only-child]:hover:ring-transparent', //select all highlighted '[&.highlighted]:rounded-none', //select first in group '[&:not(.highlighted)_+_.highlighted]:rounded-t-md', '[&:not(.highlighted)_+_.highlighted>*]:mt-1', //select last in group '[&.highlighted:has(+:not(.highlighted))]:rounded-b-md', '[&.highlighted:has(+:not(.highlighted))>*]:mb-1', //select if highlight is singular in group '[&:not(.highlighted)_+_.highlighted:has(+:not(.highlighted))]:rounded-md', line.highlighted ? ['highlighted', 'bg-dark/1', 'dark:bg-sky/1'] : null, )} > {withLineNumbers ? ( ) : null} {isLast ? null : !withLineNumbers && line.tokens.length === 0 && 0 ? ( {'\u200B'} ) : ( '\n' )} ); } function CodeHighlightTokens(props: { tokens: HighlightToken[]; document: JSONDocument; context: ContentRefContext; }) { const { tokens, document, context } = props; return ( <> {tokens.map((token, index) => ( ))} ); } function CodeHighlightToken(props: { token: HighlightToken; document: JSONDocument; context: ContentRefContext; }) { const { token, document, context } = props; if (token.type === 'inline') { return ( ); } if (token.type === 'plain') { return <>{token.content}; } if (!token.token.color) { return <>{token.token.content}; } return {token.token.content}; }