markdown.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. """Markdown component."""
  2. from __future__ import annotations
  3. import textwrap
  4. from typing import Any, Callable, Dict, Union
  5. from reflex.compiler import utils
  6. from reflex.components.component import Component, CustomComponent
  7. from reflex.components.datadisplay.list import ListItem, OrderedList, UnorderedList
  8. from reflex.components.navigation import Link
  9. from reflex.components.tags.tag import Tag
  10. from reflex.components.typography.heading import Heading
  11. from reflex.components.typography.text import Text
  12. from reflex.style import Style
  13. from reflex.utils import console, imports, types
  14. from reflex.vars import ImportVar, Var
  15. # Special vars used in the component map.
  16. _CHILDREN = Var.create_safe("children", _var_is_local=False)
  17. _PROPS = Var.create_safe("...props", _var_is_local=False)
  18. _MOCK_ARG = Var.create_safe("")
  19. # Special remark plugins.
  20. _REMARK_MATH = Var.create_safe("remarkMath", _var_is_local=False)
  21. _REMARK_GFM = Var.create_safe("remarkGfm", _var_is_local=False)
  22. _REMARK_PLUGINS = Var.create_safe([_REMARK_MATH, _REMARK_GFM])
  23. # Special rehype plugins.
  24. _REHYPE_KATEX = Var.create_safe("rehypeKatex", _var_is_local=False)
  25. _REHYPE_RAW = Var.create_safe("rehypeRaw", _var_is_local=False)
  26. _REHYPE_PLUGINS = Var.create_safe([_REHYPE_KATEX, _REHYPE_RAW])
  27. # Component Mapping
  28. def get_base_component_map() -> dict[str, Callable]:
  29. """Get the base component map.
  30. Returns:
  31. The base component map.
  32. """
  33. from reflex.components.datadisplay.code import Code, CodeBlock
  34. return {
  35. "h1": lambda value: Heading.create(
  36. value, as_="h1", size="2xl", margin_y="0.5em"
  37. ),
  38. "h2": lambda value: Heading.create(
  39. value, as_="h2", size="xl", margin_y="0.5em"
  40. ),
  41. "h3": lambda value: Heading.create(
  42. value, as_="h3", size="lg", margin_y="0.5em"
  43. ),
  44. "h4": lambda value: Heading.create(
  45. value, as_="h4", size="md", margin_y="0.5em"
  46. ),
  47. "h5": lambda value: Heading.create(
  48. value, as_="h5", size="sm", margin_y="0.5em"
  49. ),
  50. "h6": lambda value: Heading.create(
  51. value, as_="h6", size="xs", margin_y="0.5em"
  52. ),
  53. "p": lambda value: Text.create(value, margin_y="1em"),
  54. "ul": lambda value: UnorderedList.create(value, margin_y="1em"), # type: ignore
  55. "ol": lambda value: OrderedList.create(value, margin_y="1em"), # type: ignore
  56. "li": lambda value: ListItem.create(value, margin_y="0.5em"),
  57. "a": lambda value: Link.create(value),
  58. "code": lambda value: Code.create(value),
  59. "codeblock": lambda *_, **props: CodeBlock.create(
  60. theme="light", margin_y="1em", **props
  61. ),
  62. }
  63. class Markdown(Component):
  64. """A markdown component."""
  65. library = "react-markdown@8.0.7"
  66. tag = "ReactMarkdown"
  67. is_default = True
  68. # The component map from a tag to a lambda that creates a component.
  69. component_map: Dict[str, Any] = {}
  70. # Custom styles for the markdown (deprecated in v0.2.9).
  71. custom_styles: Dict[str, Any] = {}
  72. @classmethod
  73. def create(cls, *children, **props) -> Component:
  74. """Create a markdown component.
  75. Args:
  76. *children: The children of the component.
  77. **props: The properties of the component.
  78. Returns:
  79. The markdown component.
  80. """
  81. assert len(children) == 1 and types._isinstance(
  82. children[0], Union[str, Var]
  83. ), "Markdown component must have exactly one child containing the markdown source."
  84. # Custom styles are deprecated.
  85. if "custom_styles" in props:
  86. console.deprecate(
  87. "rx.markdown custom_styles",
  88. "Use the component_map prop instead.",
  89. "0.2.9",
  90. "0.3.1",
  91. )
  92. # Update the base component map with the custom component map.
  93. component_map = {**get_base_component_map(), **props.pop("component_map", {})}
  94. # Get the markdown source.
  95. src = children[0]
  96. # Dedent the source.
  97. if isinstance(src, str):
  98. src = textwrap.dedent(src)
  99. # Create the component.
  100. return super().create(src, component_map=component_map, **props)
  101. def get_custom_components(
  102. self, seen: set[str] | None = None
  103. ) -> set[CustomComponent]:
  104. """Get all the custom components used by the component.
  105. Args:
  106. seen: The tags of the components that have already been seen.
  107. Returns:
  108. The set of custom components.
  109. """
  110. custom_components = super().get_custom_components(seen=seen)
  111. # Get the custom components for each tag.
  112. for component in self.component_map.values():
  113. custom_components |= component(_MOCK_ARG).get_custom_components(seen=seen)
  114. return custom_components
  115. def _get_imports(self) -> imports.ImportDict:
  116. # Import here to avoid circular imports.
  117. from reflex.components.datadisplay.code import Code, CodeBlock
  118. imports = super()._get_imports()
  119. # Special markdown imports.
  120. imports.update(
  121. {
  122. "": [ImportVar(tag="katex/dist/katex.min.css")],
  123. "remark-math@5.1.1": [
  124. ImportVar(tag=_REMARK_MATH._var_name, is_default=True)
  125. ],
  126. "remark-gfm@3.0.1": [
  127. ImportVar(tag=_REMARK_GFM._var_name, is_default=True)
  128. ],
  129. "rehype-katex@6.0.3": [
  130. ImportVar(tag=_REHYPE_KATEX._var_name, is_default=True)
  131. ],
  132. "rehype-raw@6.1.1": [
  133. ImportVar(tag=_REHYPE_RAW._var_name, is_default=True)
  134. ],
  135. }
  136. )
  137. # Get the imports for each component.
  138. for component in self.component_map.values():
  139. imports = utils.merge_imports(imports, component(_MOCK_ARG).get_imports())
  140. # Get the imports for the code components.
  141. imports = utils.merge_imports(
  142. imports, CodeBlock.create(theme="light")._get_imports()
  143. )
  144. imports = utils.merge_imports(imports, Code.create()._get_imports())
  145. return imports
  146. def get_component(self, tag: str, **props) -> Component:
  147. """Get the component for a tag and props.
  148. Args:
  149. tag: The tag of the component.
  150. **props: The props of the component.
  151. Returns:
  152. The component.
  153. Raises:
  154. ValueError: If the tag is invalid.
  155. """
  156. # Check the tag is valid.
  157. if tag not in self.component_map:
  158. raise ValueError(f"No markdown component found for tag: {tag}.")
  159. special_props = {_PROPS}
  160. children = [_CHILDREN]
  161. # If the children are set as a prop, don't pass them as children.
  162. children_prop = props.pop("children", None)
  163. if children_prop is not None:
  164. special_props.add(Var.create_safe(f"children={str(children_prop)}"))
  165. children = []
  166. # Get the component.
  167. component = self.component_map[tag](*children, **props).set(
  168. special_props=special_props
  169. )
  170. component._add_style(Style(self.custom_styles.get(tag, {})))
  171. return component
  172. def format_component(self, tag: str, **props) -> str:
  173. """Format a component for rendering in the component map.
  174. Args:
  175. tag: The tag of the component.
  176. **props: Extra props to pass to the component function.
  177. Returns:
  178. The formatted component.
  179. """
  180. return str(self.get_component(tag, **props)).replace("\n", " ")
  181. def format_component_map(self) -> dict[str, str]:
  182. """Format the component map for rendering.
  183. Returns:
  184. The formatted component map.
  185. """
  186. components = {
  187. tag: f"{{({{{_CHILDREN._var_name}, {_PROPS._var_name}}}) => {self.format_component(tag)}}}"
  188. for tag in self.component_map
  189. }
  190. # Separate out inline code and code blocks.
  191. components[
  192. "code"
  193. ] = f"""{{({{inline, className, {_CHILDREN._var_name}, {_PROPS._var_name}}}) => {{
  194. const match = (className || '').match(/language-(?<lang>.*)/);
  195. const language = match ? match[1] : '';
  196. if (language) {{
  197. (async () => {{
  198. try {{
  199. const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{language}}`);
  200. SyntaxHighlighter.registerLanguage(language, module.default);
  201. }} catch (error) {{
  202. console.error(`Error importing language module for ${{language}}:`, error);
  203. }}
  204. }})();
  205. }}
  206. return inline ? (
  207. {self.format_component("code")}
  208. ) : (
  209. {self.format_component("codeblock", language=Var.create_safe("language", _var_is_local=False), children=Var.create_safe("String(children)", _var_is_local=False))}
  210. );
  211. }}}}""".replace(
  212. "\n", " "
  213. )
  214. return components
  215. def _render(self) -> Tag:
  216. return (
  217. super()
  218. ._render()
  219. .add_props(
  220. components=self.format_component_map(),
  221. remark_plugins=_REMARK_PLUGINS,
  222. rehype_plugins=_REHYPE_PLUGINS,
  223. )
  224. .remove_props("componentMap")
  225. )