compiler.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Compiler for the pynecone apps."""
  2. import json
  3. from typing import Type
  4. from pynecone import constants
  5. from pynecone.compiler import templates, utils
  6. from pynecone.components.component import Component, ImportDict
  7. from pynecone.state import State
  8. # Imports to be included in every Pynecone app.
  9. DEFAULT_IMPORTS: ImportDict = {
  10. "react": {"useEffect", "useState"},
  11. "next/router": {"useRouter"},
  12. f"/{constants.STATE_PATH}": {"updateState", "E"},
  13. "": {"focus-visible/dist/focus-visible"},
  14. }
  15. def compile_document_root(root: Component) -> str:
  16. """Compile the document root.
  17. Args:
  18. root: The document root to compile.
  19. Returns:
  20. The compiled document root.
  21. """
  22. return templates.DOCUMENT_ROOT(
  23. imports=utils.compile_imports(root.get_imports()),
  24. document=root.render(),
  25. )
  26. def compile_theme(theme: dict) -> str:
  27. """Compile the theme.
  28. Args:
  29. theme: The theme to compile.
  30. Returns:
  31. The compiled theme.
  32. """
  33. return templates.THEME(theme=json.dumps(theme))
  34. def compile_component(component: Component, state: Type[State]) -> str:
  35. """Compile the component given the app state.
  36. Args:
  37. component: The component to compile.
  38. state: The app state.
  39. Returns:
  40. The compiled component.
  41. """
  42. # Merge the default imports with the app-specific imports.
  43. imports = utils.merge_imports(DEFAULT_IMPORTS, component.get_imports())
  44. # Compile the code to render the component.
  45. return templates.COMPONENT(
  46. imports=utils.compile_imports(imports),
  47. custom_code=templates.join(component.get_custom_code()),
  48. constants=utils.compile_constants(),
  49. state=utils.compile_state(state),
  50. events=utils.compile_events(state),
  51. effects=utils.compile_effects(state),
  52. render=component.render(),
  53. )