markdown.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Table components."""
  2. from typing import List
  3. from pynecone import utils
  4. from pynecone.components.component import Component
  5. from pynecone.var import BaseVar, Var
  6. class Markdown(Component):
  7. """A markdown component."""
  8. library = "react-markdown"
  9. tag = "ReactMarkdown"
  10. src: Var[str]
  11. def _get_custom_code(self) -> str:
  12. return "import 'katex/dist/katex.min.css'"
  13. def _get_imports(self):
  14. imports = super()._get_imports()
  15. imports["@chakra-ui/react"] = {"Heading", "Code", "Text", "Link"}
  16. imports["react-syntax-highlighter"] = {"Prism"}
  17. imports["remark-math"] = {"remarkMath"}
  18. imports["remark-gfm"] = {"remarkGfm"}
  19. imports["rehype-katex"] = {"rehypeKatex"}
  20. return imports
  21. def _render(self):
  22. tag = super()._render()
  23. return tag.add_props(
  24. children=utils.wrap(str(self.src).strip(), "`"),
  25. components={
  26. "h1": "{({node, ...props}) => <Heading size='2xl' {...props} />}",
  27. "h2": "{({node, ...props}) => <Heading size='xl' {...props} />}",
  28. "h3": "{({node, ...props}) => <Heading size='lg' {...props} />}",
  29. "p": "{Text}",
  30. "a": "{Link}",
  31. # "code": "{Code}"
  32. "code": """{({node, inline, className, children, ...props}) =>
  33. {
  34. const match = (className || '').match(/language-(?<lang>.*)/);
  35. return !inline ? (
  36. <Prism
  37. children={String(children).replace(/\n$/, '')}
  38. language={match ? match[1] : ''}
  39. {...props}
  40. />
  41. ) : (
  42. <Code {...props}>
  43. {children}
  44. </Code>
  45. );
  46. }}""".replace(
  47. "\n", " "
  48. ),
  49. },
  50. remark_plugins=BaseVar(name="[remarkMath, remarkGfm]", type_=List[str]),
  51. rehype_plugins=BaseVar(name="[rehypeKatex]", type_=List[str]),
  52. src="",
  53. )