/ src / components / HighlightedCode.tsx
HighlightedCode.tsx
 1  import { highlight, supportsLanguage } from 'cli-highlight'
 2  import { Text } from 'ink'
 3  import React, { useMemo } from 'react'
 4  import { logError } from '../utils/log.js'
 5  
 6  type Props = {
 7    code: string
 8    language: string
 9  }
10  
11  export function HighlightedCode({ code, language }: Props): React.ReactElement {
12    const highlightedCode = useMemo(() => {
13      try {
14        if (supportsLanguage(language)) {
15          return highlight(code, { language })
16        } else {
17          logError(
18            `Language not supported while highlighting code, falling back to markdown: ${language}`,
19          )
20          return highlight(code, { language: 'markdown' })
21        }
22      } catch (e) {
23        if (e instanceof Error && e.message.includes('Unknown language')) {
24          logError(
25            `Language not supported while highlighting code, falling back to markdown: ${e}`,
26          )
27          return highlight(code, { language: 'markdown' })
28        }
29      }
30    }, [code, language])
31  
32    return <Text>{highlightedCode}</Text>
33  }