|
| 1 | +import { memo, useDeferredValue, useMemo } from 'react'; |
| 2 | +import type { TokensResult, ThemedToken } from 'shiki'; |
| 3 | + |
| 4 | +export interface TokenRendererProps { |
| 5 | + /** |
| 6 | + * The TokensResult from useShikiHighlighter with outputFormat: 'tokens' |
| 7 | + */ |
| 8 | + tokens: TokensResult; |
| 9 | + |
| 10 | + /** |
| 11 | + * Optional className for the pre element |
| 12 | + */ |
| 13 | + className?: string; |
| 14 | + |
| 15 | + /** |
| 16 | + * Optional inline styles for the pre element. |
| 17 | + * If not provided, uses tokens.rootStyle (fg/bg from theme) |
| 18 | + */ |
| 19 | + style?: React.CSSProperties; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Renders a single token as a span with inline color. |
| 24 | + * For multi-theme, uses htmlStyle which contains CSS variables. |
| 25 | + */ |
| 26 | +const Token = memo(function Token({ token }: { token: ThemedToken }) { |
| 27 | + // Prefer htmlStyle (multi-theme with CSS variables) over color (single-theme) |
| 28 | + const style = |
| 29 | + token.htmlStyle ?? (token.color ? { color: token.color } : undefined); |
| 30 | + return <span style={style}>{token.content}</span>; |
| 31 | +}); |
| 32 | + |
| 33 | +/** |
| 34 | + * Renders a line of tokens. |
| 35 | + */ |
| 36 | +const Line = memo(function Line({ |
| 37 | + tokens, |
| 38 | + isLast, |
| 39 | +}: { |
| 40 | + tokens: ThemedToken[]; |
| 41 | + isLast: boolean; |
| 42 | +}) { |
| 43 | + return ( |
| 44 | + <span className="line"> |
| 45 | + {tokens.map((token, i) => ( |
| 46 | + // biome-ignore lint/suspicious/noArrayIndexKey: tokens are positional, never reorder |
| 47 | + <Token key={i} token={token} /> |
| 48 | + ))} |
| 49 | + {!isLast && '\n'} |
| 50 | + </span> |
| 51 | + ); |
| 52 | +}); |
| 53 | + |
| 54 | +/** |
| 55 | + * Memoized token renderer with concurrent rendering support. |
| 56 | + * |
| 57 | + * Uses useDeferredValue to prevent blocking the main thread during |
| 58 | + * rapid updates (like streaming). This allows React to interrupt |
| 59 | + * rendering and keep the UI responsive. |
| 60 | + * |
| 61 | + * The component uses contentVisibility: 'auto' to skip rendering |
| 62 | + * of off-screen content, improving performance for long code blocks. |
| 63 | + * |
| 64 | + * @example |
| 65 | + * ```tsx |
| 66 | + * const tokens = useShikiHighlighter(code, 'ts', 'nord', { |
| 67 | + * outputFormat: 'tokens' |
| 68 | + * }); |
| 69 | + * |
| 70 | + * return <TokenRenderer tokens={tokens} />; |
| 71 | + * ``` |
| 72 | + */ |
| 73 | +/** |
| 74 | + * Parses Shiki's fg/bg strings which may contain CSS variables for multi-theme. |
| 75 | + * Format: "defaultValue;--css-var:value;--another-var:value" |
| 76 | + * Example: "#24292e;--shiki-dark:#e1e4e8" |
| 77 | + */ |
| 78 | +const parseThemeColor = ( |
| 79 | + colorString: string | undefined, |
| 80 | + cssProperty: 'color' | 'backgroundColor' |
| 81 | +): Record<string, string> => { |
| 82 | + if (!colorString) return {}; |
| 83 | + |
| 84 | + const result: Record<string, string> = {}; |
| 85 | + const parts = colorString.split(';'); |
| 86 | + |
| 87 | + for (const part of parts) { |
| 88 | + const trimmed = part.trim(); |
| 89 | + if (!trimmed) continue; |
| 90 | + |
| 91 | + if (trimmed.startsWith('--')) { |
| 92 | + // CSS variable: "--shiki-dark:#e1e4e8" or "--shiki-dark-bg:#24292e" |
| 93 | + const colonIndex = trimmed.indexOf(':'); |
| 94 | + if (colonIndex > 0) { |
| 95 | + const varName = trimmed.slice(0, colonIndex); |
| 96 | + const varValue = trimmed.slice(colonIndex + 1); |
| 97 | + result[varName] = varValue; |
| 98 | + } |
| 99 | + } else { |
| 100 | + // Default color value: "#24292e" |
| 101 | + result[cssProperty] = trimmed; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + return result; |
| 106 | +}; |
| 107 | + |
| 108 | +export const TokenRenderer = memo(function TokenRenderer({ |
| 109 | + tokens, |
| 110 | + className, |
| 111 | + style, |
| 112 | +}: TokenRendererProps) { |
| 113 | + // Defer token updates to prevent blocking during streaming |
| 114 | + const deferredTokens = useDeferredValue(tokens); |
| 115 | + |
| 116 | + // Parse fg/bg into CSSProperties, handling multi-theme CSS variables |
| 117 | + const baseStyle = useMemo((): React.CSSProperties => { |
| 118 | + const parsed: Record<string, string> = { |
| 119 | + // Enable content-visibility for off-screen optimization |
| 120 | + contentVisibility: 'auto', |
| 121 | + }; |
| 122 | + |
| 123 | + // Parse fg (e.g., "#24292e;--shiki-dark:#e1e4e8") |
| 124 | + Object.assign(parsed, parseThemeColor(deferredTokens.fg, 'color')); |
| 125 | + |
| 126 | + // Parse bg (e.g., "#fff;--shiki-dark-bg:#24292e") |
| 127 | + Object.assign( |
| 128 | + parsed, |
| 129 | + parseThemeColor(deferredTokens.bg, 'backgroundColor') |
| 130 | + ); |
| 131 | + |
| 132 | + // Also parse rootStyle for single-theme fallback |
| 133 | + if (deferredTokens.rootStyle) { |
| 134 | + const parts = deferredTokens.rootStyle.split(';'); |
| 135 | + for (const part of parts) { |
| 136 | + const [key, value] = part.split(':'); |
| 137 | + if (key && value) { |
| 138 | + const camelKey = key |
| 139 | + .trim() |
| 140 | + .replace(/-([a-z])/g, (_, c) => c.toUpperCase()); |
| 141 | + parsed[camelKey] = value.trim(); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + return parsed as React.CSSProperties; |
| 147 | + }, [deferredTokens.fg, deferredTokens.bg, deferredTokens.rootStyle]); |
| 148 | + |
| 149 | + const mergedStyle = style ? { ...baseStyle, ...style } : baseStyle; |
| 150 | + const preClass = className ? `shiki ${className}` : 'shiki'; |
| 151 | + |
| 152 | + return ( |
| 153 | + <pre className={preClass} style={mergedStyle}> |
| 154 | + <code> |
| 155 | + {deferredTokens.tokens.map((lineTokens, i) => ( |
| 156 | + <Line |
| 157 | + // biome-ignore lint/suspicious/noArrayIndexKey: lines are positional, never reorder |
| 158 | + key={i} |
| 159 | + tokens={lineTokens} |
| 160 | + isLast={i === deferredTokens.tokens.length - 1} |
| 161 | + /> |
| 162 | + ))} |
| 163 | + </code> |
| 164 | + </pre> |
| 165 | + ); |
| 166 | +}); |
0 commit comments