compiler.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. from typing import List, Set, Tuple, Type
  4. from reflex import constants
  5. from reflex.compiler import templates, utils
  6. from reflex.components.component import Component, ComponentStyle, CustomComponent
  7. from reflex.state import State
  8. from reflex.utils import imports
  9. from reflex.vars import ImportVar
  10. # Imports to be included in every Reflex app.
  11. DEFAULT_IMPORTS: imports.ImportDict = {
  12. "react": {
  13. ImportVar(tag="Fragment"),
  14. ImportVar(tag="useEffect"),
  15. ImportVar(tag="useRef"),
  16. ImportVar(tag="useState"),
  17. ImportVar(tag="useContext"),
  18. },
  19. "next/router": {ImportVar(tag="useRouter")},
  20. f"/{constants.STATE_PATH}": {
  21. ImportVar(tag="uploadFiles"),
  22. ImportVar(tag="E"),
  23. ImportVar(tag="isTrue"),
  24. ImportVar(tag="preventDefault"),
  25. ImportVar(tag="refs"),
  26. ImportVar(tag="getRefValue"),
  27. ImportVar(tag="getRefValues"),
  28. ImportVar(tag="getAllLocalStorageItems"),
  29. ImportVar(tag="useEventLoop"),
  30. },
  31. "/utils/context.js": {
  32. ImportVar(tag="EventLoopContext"),
  33. ImportVar(tag="StateContext"),
  34. },
  35. "": {ImportVar(tag="focus-visible/dist/focus-visible")},
  36. "@chakra-ui/react": {
  37. ImportVar(tag=constants.USE_COLOR_MODE),
  38. ImportVar(tag="Box"),
  39. ImportVar(tag="Text"),
  40. },
  41. }
  42. def _compile_document_root(root: Component) -> str:
  43. """Compile the document root.
  44. Args:
  45. root: The document root to compile.
  46. Returns:
  47. The compiled document root.
  48. """
  49. return templates.DOCUMENT_ROOT.render(
  50. imports=utils.compile_imports(root.get_imports()),
  51. document=root.render(),
  52. )
  53. def _compile_theme(theme: dict) -> str:
  54. """Compile the theme.
  55. Args:
  56. theme: The theme to compile.
  57. Returns:
  58. The compiled theme.
  59. """
  60. return templates.THEME.render(theme=theme)
  61. def _compile_contexts(state: Type[State]) -> str:
  62. """Compile the initial state and contexts.
  63. Args:
  64. state: The app state.
  65. Returns:
  66. The compiled context file.
  67. """
  68. return templates.CONTEXT.render(
  69. initial_state=utils.compile_state(state),
  70. state_name=state.get_name(),
  71. )
  72. def _compile_page(
  73. component: Component,
  74. state: Type[State],
  75. connect_error_component,
  76. ) -> str:
  77. """Compile the component given the app state.
  78. Args:
  79. component: The component to compile.
  80. state: The app state.
  81. connect_error_component: The component to render on sever connection error.
  82. Returns:
  83. The compiled component.
  84. """
  85. # Merge the default imports with the app-specific imports.
  86. imports = utils.merge_imports(DEFAULT_IMPORTS, component.get_imports())
  87. utils.validate_imports(imports)
  88. imports = utils.compile_imports(imports)
  89. # Compile the code to render the component.
  90. return templates.PAGE.render(
  91. imports=imports,
  92. custom_codes=component.get_custom_code(),
  93. state_name=state.get_name(),
  94. hooks=component.get_hooks(),
  95. render=component.render(),
  96. transports=constants.Transports.POLLING_WEBSOCKET.get_transports(),
  97. err_comp=connect_error_component.render() if connect_error_component else None,
  98. )
  99. def _compile_components(components: Set[CustomComponent]) -> str:
  100. """Compile the components.
  101. Args:
  102. components: The components to compile.
  103. Returns:
  104. The compiled components.
  105. """
  106. imports = {
  107. "react": {ImportVar(tag="memo")},
  108. f"/{constants.STATE_PATH}": {ImportVar(tag="E"), ImportVar(tag="isTrue")},
  109. }
  110. component_renders = []
  111. # Compile each component.
  112. for component in components:
  113. component_render, component_imports = utils.compile_custom_component(component)
  114. component_renders.append(component_render)
  115. imports = utils.merge_imports(imports, component_imports)
  116. # Compile the components page.
  117. return templates.COMPONENTS.render(
  118. imports=utils.compile_imports(imports),
  119. components=component_renders,
  120. )
  121. def _compile_tailwind(
  122. config: dict,
  123. ) -> str:
  124. """Compile the Tailwind config.
  125. Args:
  126. config: The Tailwind config.
  127. Returns:
  128. The compiled Tailwind config.
  129. """
  130. return templates.TAILWIND_CONFIG.render(
  131. **config,
  132. )
  133. def compile_document_root(stylesheets: List[str]) -> Tuple[str, str]:
  134. """Compile the document root.
  135. Args:
  136. stylesheets: The stylesheets to include in the document root.
  137. Returns:
  138. The path and code of the compiled document root.
  139. """
  140. # Get the path for the output file.
  141. output_path = utils.get_page_path(constants.DOCUMENT_ROOT)
  142. # Create the document root.
  143. document_root = utils.create_document_root(stylesheets)
  144. # Compile the document root.
  145. code = _compile_document_root(document_root)
  146. return output_path, code
  147. def compile_theme(style: ComponentStyle) -> Tuple[str, str]:
  148. """Compile the theme.
  149. Args:
  150. style: The style to compile.
  151. Returns:
  152. The path and code of the compiled theme.
  153. """
  154. output_path = utils.get_theme_path()
  155. # Create the theme.
  156. theme = utils.create_theme(style)
  157. # Compile the theme.
  158. code = _compile_theme(theme)
  159. return output_path, code
  160. def compile_contexts(
  161. state: Type[State],
  162. ) -> Tuple[str, str]:
  163. """Compile the initial state / context.
  164. Args:
  165. state: The app state.
  166. Returns:
  167. The path and code of the compiled context.
  168. """
  169. # Get the path for the output file.
  170. output_path = utils.get_context_path()
  171. return output_path, _compile_contexts(state)
  172. def compile_page(
  173. path: str,
  174. component: Component,
  175. state: Type[State],
  176. connect_error_component: Component,
  177. ) -> Tuple[str, str]:
  178. """Compile a single page.
  179. Args:
  180. path: The path to compile the page to.
  181. component: The component to compile.
  182. state: The app state.
  183. connect_error_component: The component to render on sever connection error.
  184. Returns:
  185. The path and code of the compiled page.
  186. """
  187. # Get the path for the output file.
  188. output_path = utils.get_page_path(path)
  189. # Add the style to the component.
  190. code = _compile_page(
  191. component,
  192. state,
  193. connect_error_component,
  194. )
  195. return output_path, code
  196. def compile_components(components: Set[CustomComponent]):
  197. """Compile the custom components.
  198. Args:
  199. components: The custom components to compile.
  200. Returns:
  201. The path and code of the compiled components.
  202. """
  203. # Get the path for the output file.
  204. output_path = utils.get_components_path()
  205. # Compile the components.
  206. code = _compile_components(components)
  207. return output_path, code
  208. def compile_tailwind(
  209. config: dict,
  210. ):
  211. """Compile the Tailwind config.
  212. Args:
  213. config: The Tailwind config.
  214. Returns:
  215. The compiled Tailwind config.
  216. """
  217. # Get the path for the output file.
  218. output_path = constants.TAILWIND_CONFIG
  219. # Compile the config.
  220. code = _compile_tailwind(config)
  221. return output_path, code
  222. def purge_web_pages_dir():
  223. """Empty out .web directory."""
  224. template_files = ["_app.js", "404.js"]
  225. utils.empty_dir(constants.WEB_PAGES_DIR, keep_files=template_files)