code.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """A code component."""
  2. from typing import Dict
  3. from pynecone import utils
  4. from pynecone.components.component import Component, ImportDict
  5. from pynecone.components.libs.chakra import ChakraComponent
  6. from pynecone.var import Var
  7. # Path to the prism styles.
  8. PRISM_STYLES_PATH = "/styles/code/prism"
  9. class CodeBlock(Component):
  10. """A code block."""
  11. library = "react-syntax-highlighter"
  12. tag = "Prism"
  13. # The theme to use.
  14. theme: Var[str]
  15. # The language to use.
  16. language: Var[str]
  17. # If this is enabled line numbers will be shown next to the code block.
  18. show_line_numbers: Var[bool]
  19. # The starting line number to use.
  20. starting_line_number: Var[int]
  21. # Whether to wrap long lines.
  22. wrap_long_lines: Var[bool]
  23. # A custom style for the code block.
  24. custom_style: Var[Dict[str, str]]
  25. # Props passed down to the code tag.
  26. code_tag_props: Var[Dict[str, str]]
  27. def _get_imports(self) -> ImportDict:
  28. imports = super()._get_imports()
  29. if self.theme is not None:
  30. imports = utils.merge_imports(
  31. imports, {PRISM_STYLES_PATH: {self.theme.name}}
  32. )
  33. return imports
  34. @classmethod
  35. def create(cls, *children, **props):
  36. """Create a text component.
  37. Args:
  38. *children: The children of the component.
  39. **props: The props to pass to the component.
  40. Returns:
  41. The text component.
  42. """
  43. # This component handles style in a special prop.
  44. custom_style = props.get("custom_style", {})
  45. # Transfer style props to the custom style prop.
  46. for key, value in props.items():
  47. if key not in cls.get_fields():
  48. custom_style[key] = value
  49. # Create the component.
  50. return super().create(
  51. *children,
  52. **props,
  53. )
  54. def _add_style(self, style):
  55. self.custom_style = self.custom_style or {}
  56. self.custom_style.update(style) # type: ignore
  57. def _render(self):
  58. out = super()._render()
  59. if self.theme is not None:
  60. out.add_props(
  61. style=Var.create(self.theme.name, is_local=False)
  62. ).remove_props("theme")
  63. return out
  64. class Code(ChakraComponent):
  65. """Used to display inline code."""
  66. tag = "Code"