( node: Root | Element | HastText | RootContent, theme: Theme, inheritedColor: string | undefined, )
| 27 | const lowlight = createLowlight(common); |
| 28 | |
| 29 | function renderHastNode( |
| 30 | node: Root | Element | HastText | RootContent, |
| 31 | theme: Theme, |
| 32 | inheritedColor: string | undefined, |
| 33 | ): React.ReactNode { |
| 34 | if (node.type === 'text') { |
| 35 | // Use the color passed down from parent element, if any |
| 36 | return <Text color={inheritedColor}>{node.value}</Text>; |
| 37 | } |
| 38 | |
| 39 | // Handle Element Nodes: Determine color and pass it down, don't wrap |
| 40 | if (node.type === 'element') { |
| 41 | const nodeClasses: string[] = |
| 42 | (node.properties?.['className'] as string[]) || []; |
| 43 | let elementColor: string | undefined = undefined; |
| 44 | |
| 45 | // Find color defined specifically for this element's class |
| 46 | for (let i = nodeClasses.length - 1; i >= 0; i--) { |
| 47 | const color = theme.getInkColor(nodeClasses[i]); |
| 48 | if (color) { |
| 49 | elementColor = color; |
| 50 | break; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // Determine the color to pass down: Use this element's specific color |
| 55 | // if found; otherwise, continue passing down the already inherited color. |
| 56 | const colorToPassDown = elementColor || inheritedColor; |
| 57 | |
| 58 | // Recursively render children, passing the determined color down |
| 59 | // Ensure child type matches expected HAST structure (ElementContent is common) |
| 60 | const children = node.children?.map( |
| 61 | (child: ElementContent, index: number) => ( |
| 62 | <React.Fragment key={index}> |
| 63 | {renderHastNode(child, theme, colorToPassDown)} |
| 64 | </React.Fragment> |
| 65 | ), |
| 66 | ); |
| 67 | |
| 68 | // Element nodes now only group children; color is applied by Text nodes. |
| 69 | // Use a React Fragment to avoid adding unnecessary elements. |
| 70 | return <React.Fragment>{children}</React.Fragment>; |
| 71 | } |
| 72 | |
| 73 | // Handle Root Node: Start recursion with initially inherited color |
| 74 | if (node.type === 'root') { |
| 75 | // Check if children array is empty - this happens when lowlight can't detect language – fall back to plain text |
| 76 | if (!node.children || node.children.length === 0) { |
| 77 | return null; |
| 78 | } |
| 79 | |
| 80 | // Pass down the initial inheritedColor (likely undefined from the top call) |
| 81 | // Ensure child type matches expected HAST structure (RootContent is common) |
| 82 | return node.children?.map((child: RootContent, index: number) => ( |
| 83 | <React.Fragment key={index}> |
| 84 | {renderHastNode(child, theme, inheritedColor)} |
| 85 | </React.Fragment> |
| 86 | )); |
no test coverage detected