compiler.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. import os
  4. from pathlib import Path
  5. from typing import Type
  6. from reflex import constants
  7. from reflex.compiler import templates, utils
  8. from reflex.components.component import Component, ComponentStyle, CustomComponent
  9. from reflex.config import get_config
  10. from reflex.state import State
  11. from reflex.utils import imports
  12. from reflex.vars import ImportVar
  13. # Imports to be included in every Reflex app.
  14. DEFAULT_IMPORTS: imports.ImportDict = {
  15. "react": {
  16. ImportVar(tag="Fragment"),
  17. ImportVar(tag="useEffect"),
  18. ImportVar(tag="useRef"),
  19. ImportVar(tag="useState"),
  20. ImportVar(tag="useContext"),
  21. },
  22. "next/router": {ImportVar(tag="useRouter")},
  23. f"/{constants.Dirs.STATE_PATH}": {
  24. ImportVar(tag="uploadFiles"),
  25. ImportVar(tag="Event"),
  26. ImportVar(tag="isTrue"),
  27. ImportVar(tag="spreadArraysOrObjects"),
  28. ImportVar(tag="preventDefault"),
  29. ImportVar(tag="refs"),
  30. ImportVar(tag="getRefValue"),
  31. ImportVar(tag="getRefValues"),
  32. ImportVar(tag="getAllLocalStorageItems"),
  33. ImportVar(tag="useEventLoop"),
  34. },
  35. "/utils/context.js": {
  36. ImportVar(tag="EventLoopContext"),
  37. ImportVar(tag="initialEvents"),
  38. ImportVar(tag="StateContext"),
  39. },
  40. "": {ImportVar(tag="focus-visible/dist/focus-visible", install=False)},
  41. "@chakra-ui/react": {
  42. ImportVar(tag=constants.ColorMode.USE),
  43. ImportVar(tag="Box"),
  44. ImportVar(tag="Text"),
  45. },
  46. }
  47. def _compile_document_root(root: Component) -> str:
  48. """Compile the document root.
  49. Args:
  50. root: The document root to compile.
  51. Returns:
  52. The compiled document root.
  53. """
  54. return templates.DOCUMENT_ROOT.render(
  55. imports=utils.compile_imports(root.get_imports()),
  56. document=root.render(),
  57. )
  58. def _compile_theme(theme: dict) -> str:
  59. """Compile the theme.
  60. Args:
  61. theme: The theme to compile.
  62. Returns:
  63. The compiled theme.
  64. """
  65. return templates.THEME.render(theme=theme)
  66. def _compile_contexts(state: Type[State]) -> str:
  67. """Compile the initial state and contexts.
  68. Args:
  69. state: The app state.
  70. Returns:
  71. The compiled context file.
  72. """
  73. return templates.CONTEXT.render(
  74. initial_state=utils.compile_state(state),
  75. state_name=state.get_name(),
  76. client_storage=utils.compile_client_storage(state),
  77. )
  78. def _compile_page(
  79. component: Component,
  80. state: Type[State],
  81. ) -> str:
  82. """Compile the component given the app state.
  83. Args:
  84. component: The component to compile.
  85. state: The app state.
  86. Returns:
  87. The compiled component.
  88. """
  89. # Merge the default imports with the app-specific imports.
  90. imports = utils.merge_imports(DEFAULT_IMPORTS, component.get_imports())
  91. utils.validate_imports(imports)
  92. imports = utils.compile_imports(imports)
  93. # Compile the code to render the component.
  94. return templates.PAGE.render(
  95. imports=imports,
  96. dynamic_imports=component.get_dynamic_imports(),
  97. custom_codes=component.get_custom_code(),
  98. state_name=state.get_name(),
  99. hooks=component.get_hooks(),
  100. render=component.render(),
  101. )
  102. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  103. """Compile the root stylesheet.
  104. Args:
  105. stylesheets: The stylesheets to include in the root stylesheet.
  106. Returns:
  107. The path and code of the compiled root stylesheet.
  108. """
  109. output_path = utils.get_root_stylesheet_path()
  110. code = _compile_root_stylesheet(stylesheets)
  111. return output_path, code
  112. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  113. """Compile the root stylesheet.
  114. Args:
  115. stylesheets: The stylesheets to include in the root stylesheet.
  116. Returns:
  117. The compiled root stylesheet.
  118. Raises:
  119. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  120. """
  121. # Add tailwind css if enabled.
  122. sheets = (
  123. [constants.Tailwind.ROOT_STYLE_PATH]
  124. if get_config().tailwind is not None
  125. else []
  126. )
  127. for stylesheet in stylesheets:
  128. if not utils.is_valid_url(stylesheet):
  129. # check if stylesheet provided exists.
  130. stylesheet_full_path = (
  131. Path.cwd() / constants.Dirs.APP_ASSETS / stylesheet.strip("/")
  132. )
  133. if not os.path.exists(stylesheet_full_path):
  134. raise FileNotFoundError(
  135. f"The stylesheet file {stylesheet_full_path} does not exist."
  136. )
  137. stylesheet = f"@/{stylesheet.strip('/')}"
  138. sheets.append(stylesheet) if stylesheet not in sheets else None
  139. return templates.STYLE.render(stylesheets=sheets)
  140. def _compile_component(component: Component) -> str:
  141. """Compile a single component.
  142. Args:
  143. component: The component to compile.
  144. Returns:
  145. The compiled component.
  146. """
  147. return templates.COMPONENT.render(component=component)
  148. def _compile_components(components: set[CustomComponent]) -> str:
  149. """Compile the components.
  150. Args:
  151. components: The components to compile.
  152. Returns:
  153. The compiled components.
  154. """
  155. imports = {
  156. "react": {ImportVar(tag="memo")},
  157. f"/{constants.Dirs.STATE_PATH}": {ImportVar(tag="E"), ImportVar(tag="isTrue")},
  158. }
  159. component_renders = []
  160. # Compile each component.
  161. for component in components:
  162. component_render, component_imports = utils.compile_custom_component(component)
  163. component_renders.append(component_render)
  164. imports = utils.merge_imports(imports, component_imports)
  165. # Compile the components page.
  166. return templates.COMPONENTS.render(
  167. imports=utils.compile_imports(imports),
  168. components=component_renders,
  169. )
  170. def _compile_tailwind(
  171. config: dict,
  172. ) -> str:
  173. """Compile the Tailwind config.
  174. Args:
  175. config: The Tailwind config.
  176. Returns:
  177. The compiled Tailwind config.
  178. """
  179. return templates.TAILWIND_CONFIG.render(
  180. **config,
  181. )
  182. def compile_document_root(head_components: list[Component]) -> tuple[str, str]:
  183. """Compile the document root.
  184. Args:
  185. head_components: The components to include in the head.
  186. Returns:
  187. The path and code of the compiled document root.
  188. """
  189. # Get the path for the output file.
  190. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  191. # Create the document root.
  192. document_root = utils.create_document_root(head_components)
  193. # Compile the document root.
  194. code = _compile_document_root(document_root)
  195. return output_path, code
  196. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  197. """Compile the theme.
  198. Args:
  199. style: The style to compile.
  200. Returns:
  201. The path and code of the compiled theme.
  202. """
  203. output_path = utils.get_theme_path()
  204. # Create the theme.
  205. theme = utils.create_theme(style)
  206. # Compile the theme.
  207. code = _compile_theme(theme)
  208. return output_path, code
  209. def compile_contexts(state: Type[State]) -> tuple[str, str]:
  210. """Compile the initial state / context.
  211. Args:
  212. state: The app state.
  213. Returns:
  214. The path and code of the compiled context.
  215. """
  216. # Get the path for the output file.
  217. output_path = utils.get_context_path()
  218. return output_path, _compile_contexts(state)
  219. def compile_page(
  220. path: str, component: Component, state: Type[State]
  221. ) -> tuple[str, str]:
  222. """Compile a single page.
  223. Args:
  224. path: The path to compile the page to.
  225. component: The component to compile.
  226. state: The app state.
  227. Returns:
  228. The path and code of the compiled page.
  229. """
  230. # Get the path for the output file.
  231. output_path = utils.get_page_path(path)
  232. # Add the style to the component.
  233. code = _compile_page(component, state)
  234. return output_path, code
  235. def compile_components(components: set[CustomComponent]):
  236. """Compile the custom components.
  237. Args:
  238. components: The custom components to compile.
  239. Returns:
  240. The path and code of the compiled components.
  241. """
  242. # Get the path for the output file.
  243. output_path = utils.get_components_path()
  244. # Compile the components.
  245. code = _compile_components(components)
  246. return output_path, code
  247. def compile_tailwind(
  248. config: dict,
  249. ):
  250. """Compile the Tailwind config.
  251. Args:
  252. config: The Tailwind config.
  253. Returns:
  254. The compiled Tailwind config.
  255. """
  256. # Get the path for the output file.
  257. output_path = constants.Tailwind.CONFIG
  258. # Compile the config.
  259. code = _compile_tailwind(config)
  260. return output_path, code
  261. def purge_web_pages_dir():
  262. """Empty out .web directory."""
  263. utils.empty_dir(constants.Dirs.WEB_PAGES, keep_files=["_app.js"])