import { DocumentBlockCode, JSONDocument } from '@gitbook/api'; import { tcls } from '@/lib/tailwind'; import { CopyCodeButton } from './CopyCodeButton'; import { highlight, HighlightLine, HighlightToken, plainHighlighting } from './highlight'; import { BlockProps } from '../Block'; import { DocumentContext } from '../DocumentView'; 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 withHighlighting = context.shouldHighlightCode(context.content?.spaceId); const lines = withHighlighting ? await highlight(block) : plainHighlighting(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 titleRoundingStyle = [ 'rounded-md', 'straight-corners:rounded-sm', title ? 'rounded-ss-none' : null, ]; 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: DocumentContext; }) { 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-light-3', 'dark:bg-dark-3'] : null, )} > {withLineNumbers ? ( ) : null} {isLast ? null : !withLineNumbers && line.tokens.length === 0 && 0 ? ( {'\u200B'} ) : ( '\n' )} ); } function CodeHighlightTokens(props: { tokens: HighlightToken[]; document: JSONDocument; context: DocumentContext; }) { const { tokens, document, context } = props; return ( <> {tokens.map((token, index) => ( ))} ); } function CodeHighlightToken(props: { token: HighlightToken; document: JSONDocument; context: DocumentContext; }) { 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}; }