iamacup / react-native-markdown-display

React Native 100% compatible CommonMark renderer
MIT License
590 stars 169 forks source link

Added sourceInfo and sourceMeta to ASTNode #132

Open ahkhanjani opened 3 years ago

ahkhanjani commented 3 years ago

In case you need syntax highlighting with Prism or something similar, you need to get the language of the code via node.sourceInfo like this:

<Markdown
  rules={{
    // markdown-it renders code blocks as "fence".
    fence: (node) => {
      return (
        <CodeBlock
          key={node.key}
          plainCode={node.content}

          // Get the language
          lang={node.sourceInfo}
        />
      );
    },
  }}
>
  {wholeMarkdown}
</Markdown>

And then the component:

import Prism from 'prismjs';

interface Props {
  plainCode: string;
  lang: string;
}

const CodeBlock: React.FC<Props> = ({ plainCode, lang }) => {
  let highlightedCode: string = '';
  try {
    highlightedCode = Prism.highlight(plainCode, Prism.languages[lang], lang);
  } catch (_) {
    highlightedCode = plainCode;
  }

  return (
    <View>
      // Use react-native-webview to show the highlighted code.
    </View>
  );
};

Edit: Added sourceMeta as requested in #130.

zecakeh commented 3 years ago

Maybe you could add also sourceMeta like I requested in #130? :pray: