( code: string, language: string = "javascript", theme: SyntaxHighlighterTheme = defaultTheme, )
| 80 | }; |
| 81 | |
| 82 | export function highlightCode( |
| 83 | code: string, |
| 84 | language: string = "javascript", |
| 85 | theme: SyntaxHighlighterTheme = defaultTheme, |
| 86 | ): React.ReactNode[] { |
| 87 | try { |
| 88 | // Create lowlight instance with common languages |
| 89 | const lowlight = createLowlight(common); |
| 90 | |
| 91 | const result = lowlight.highlight(language, code, { prefix: "" }); |
| 92 | |
| 93 | // Convert the hast tree to React elements |
| 94 | const elements: React.ReactNode[] = []; |
| 95 | |
| 96 | let keyCounter = 0; |
| 97 | |
| 98 | function processNode( |
| 99 | node: any, |
| 100 | parentColor: string = theme.default, |
| 101 | ): React.ReactNode { |
| 102 | if (node.type === "text") { |
| 103 | const text = node.value; |
| 104 | if (text) { |
| 105 | return React.createElement( |
| 106 | Text, |
| 107 | { |
| 108 | key: `text-${keyCounter++}`, |
| 109 | color: parentColor, |
| 110 | }, |
| 111 | text, |
| 112 | ); |
| 113 | } |
| 114 | return null; |
| 115 | } |
| 116 | |
| 117 | if (node.type === "element") { |
| 118 | const className = node.properties?.className || []; |
| 119 | |
| 120 | // Extract token type from class names |
| 121 | let tokenType = ""; |
| 122 | for (const cls of className) { |
| 123 | if (tokenColorMap[cls]) { |
| 124 | tokenType = cls; |
| 125 | break; |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // Get color from theme |
| 130 | const colorKey = tokenColorMap[tokenType] || "default"; |
| 131 | const color = theme[colorKey]; |
| 132 | |
| 133 | if (node.children && node.children.length > 0) { |
| 134 | // Process child nodes with this color |
| 135 | const children: React.ReactNode[] = []; |
| 136 | for (let i = 0; i < node.children.length; i++) { |
| 137 | const child = processNode(node.children[i], color); |
| 138 | if (!child) continue; |
| 139 |
no test coverage detected