compiler.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. import os
  4. from pathlib import Path
  5. from typing import Iterable, Optional, Type
  6. from reflex import constants
  7. from reflex.compiler import templates, utils
  8. from reflex.components.component import (
  9. BaseComponent,
  10. Component,
  11. ComponentStyle,
  12. CustomComponent,
  13. StatefulComponent,
  14. )
  15. from reflex.config import get_config
  16. from reflex.state import State
  17. from reflex.utils.imports import ImportDict, ImportVar
  18. # Imports to be included in every Reflex app.
  19. DEFAULT_IMPORTS: ImportDict = {
  20. "": [ImportVar(tag="focus-visible/dist/focus-visible", install=False)],
  21. }
  22. def _compile_document_root(root: Component) -> str:
  23. """Compile the document root.
  24. Args:
  25. root: The document root to compile.
  26. Returns:
  27. The compiled document root.
  28. """
  29. return templates.DOCUMENT_ROOT.render(
  30. imports=utils.compile_imports(root.get_imports()),
  31. document=root.render(),
  32. )
  33. def _compile_app(app_root: Component) -> str:
  34. """Compile the app template component.
  35. Args:
  36. app_root: The app root to compile.
  37. Returns:
  38. The compiled app.
  39. """
  40. return templates.APP_ROOT.render(
  41. imports=utils.compile_imports(app_root.get_imports()),
  42. custom_codes=app_root.get_custom_code(),
  43. hooks=app_root.get_hooks(),
  44. render=app_root.render(),
  45. )
  46. def _compile_theme(theme: dict) -> str:
  47. """Compile the theme.
  48. Args:
  49. theme: The theme to compile.
  50. Returns:
  51. The compiled theme.
  52. """
  53. return templates.THEME.render(theme=theme)
  54. def _compile_contexts(state: Optional[Type[State]]) -> str:
  55. """Compile the initial state and contexts.
  56. Args:
  57. state: The app state.
  58. Returns:
  59. The compiled context file.
  60. """
  61. is_dev_mode = os.environ.get("REFLEX_ENV_MODE", "dev") == "dev"
  62. return (
  63. templates.CONTEXT.render(
  64. initial_state=utils.compile_state(state),
  65. state_name=state.get_name(),
  66. client_storage=utils.compile_client_storage(state),
  67. is_dev_mode=is_dev_mode,
  68. )
  69. if state
  70. else templates.CONTEXT.render(is_dev_mode=is_dev_mode)
  71. )
  72. def _compile_page(
  73. component: Component,
  74. state: Type[State],
  75. ) -> str:
  76. """Compile the component given the app state.
  77. Args:
  78. component: The component to compile.
  79. state: The app state.
  80. Returns:
  81. The compiled component.
  82. """
  83. # Merge the default imports with the app-specific imports.
  84. imports = utils.merge_imports(DEFAULT_IMPORTS, component.get_imports())
  85. imports = utils.compile_imports(imports)
  86. # Compile the code to render the component.
  87. kwargs = {"state_name": state.get_name()} if state else {}
  88. return templates.PAGE.render(
  89. imports=imports,
  90. dynamic_imports=component.get_dynamic_imports(),
  91. custom_codes=component.get_custom_code(),
  92. hooks=component.get_hooks(),
  93. render=component.render(),
  94. **kwargs,
  95. )
  96. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  97. """Compile the root stylesheet.
  98. Args:
  99. stylesheets: The stylesheets to include in the root stylesheet.
  100. Returns:
  101. The path and code of the compiled root stylesheet.
  102. """
  103. output_path = utils.get_root_stylesheet_path()
  104. code = _compile_root_stylesheet(stylesheets)
  105. return output_path, code
  106. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  107. """Compile the root stylesheet.
  108. Args:
  109. stylesheets: The stylesheets to include in the root stylesheet.
  110. Returns:
  111. The compiled root stylesheet.
  112. Raises:
  113. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  114. """
  115. # Add tailwind css if enabled.
  116. sheets = (
  117. [constants.Tailwind.ROOT_STYLE_PATH]
  118. if get_config().tailwind is not None
  119. else []
  120. )
  121. for stylesheet in stylesheets:
  122. if not utils.is_valid_url(stylesheet):
  123. # check if stylesheet provided exists.
  124. stylesheet_full_path = (
  125. Path.cwd() / constants.Dirs.APP_ASSETS / stylesheet.strip("/")
  126. )
  127. if not os.path.exists(stylesheet_full_path):
  128. raise FileNotFoundError(
  129. f"The stylesheet file {stylesheet_full_path} does not exist."
  130. )
  131. stylesheet = f"@/{stylesheet.strip('/')}"
  132. sheets.append(stylesheet) if stylesheet not in sheets else None
  133. return templates.STYLE.render(stylesheets=sheets)
  134. def _compile_component(component: Component) -> str:
  135. """Compile a single component.
  136. Args:
  137. component: The component to compile.
  138. Returns:
  139. The compiled component.
  140. """
  141. return templates.COMPONENT.render(component=component)
  142. def _compile_components(components: set[CustomComponent]) -> str:
  143. """Compile the components.
  144. Args:
  145. components: The components to compile.
  146. Returns:
  147. The compiled components.
  148. """
  149. imports = {
  150. "react": [ImportVar(tag="memo")],
  151. f"/{constants.Dirs.STATE_PATH}": [ImportVar(tag="E"), ImportVar(tag="isTrue")],
  152. }
  153. component_renders = []
  154. # Compile each component.
  155. for component in components:
  156. component_render, component_imports = utils.compile_custom_component(component)
  157. component_renders.append(component_render)
  158. imports = utils.merge_imports(imports, component_imports)
  159. # Compile the components page.
  160. return templates.COMPONENTS.render(
  161. imports=utils.compile_imports(imports),
  162. components=component_renders,
  163. )
  164. def _compile_stateful_components(
  165. page_components: list[BaseComponent],
  166. ) -> str:
  167. """Walk the page components and extract shared stateful components.
  168. Any StatefulComponent that is shared by more than one page will be rendered
  169. to a separate module and marked rendered_as_shared so subsequent
  170. renderings will import the component from the shared module instead of
  171. directly including the code for it.
  172. Args:
  173. page_components: The Components or StatefulComponents to compile.
  174. Returns:
  175. The rendered stateful components code.
  176. """
  177. all_import_dicts = []
  178. rendered_components = {}
  179. def get_shared_components_recursive(component: BaseComponent):
  180. """Get the shared components for a component and its children.
  181. A shared component is a StatefulComponent that appears in 2 or more
  182. pages and is a candidate for writing to a common file and importing
  183. into each page where it is used.
  184. Args:
  185. component: The component to collect shared StatefulComponents for.
  186. """
  187. for child in component.children:
  188. # Depth-first traversal.
  189. get_shared_components_recursive(child)
  190. # When the component is referenced by more than one page, render it
  191. # to be included in the STATEFUL_COMPONENTS module.
  192. if isinstance(component, StatefulComponent) and component.references > 1:
  193. # Reset this flag to render the actual component.
  194. component.rendered_as_shared = False
  195. rendered_components.update(
  196. {code: None for code in component.get_custom_code()},
  197. )
  198. all_import_dicts.append(component.get_imports())
  199. # Indicate that this component now imports from the shared file.
  200. component.rendered_as_shared = True
  201. for page_component in page_components:
  202. get_shared_components_recursive(page_component)
  203. # Don't import from the file that we're about to create.
  204. all_imports = utils.merge_imports(*all_import_dicts)
  205. all_imports.pop(
  206. f"/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
  207. )
  208. return templates.STATEFUL_COMPONENTS.render(
  209. imports=utils.compile_imports(all_imports),
  210. memoized_code="\n".join(rendered_components),
  211. )
  212. def _compile_tailwind(
  213. config: dict,
  214. ) -> str:
  215. """Compile the Tailwind config.
  216. Args:
  217. config: The Tailwind config.
  218. Returns:
  219. The compiled Tailwind config.
  220. """
  221. return templates.TAILWIND_CONFIG.render(
  222. **config,
  223. )
  224. def compile_document_root(head_components: list[Component]) -> tuple[str, str]:
  225. """Compile the document root.
  226. Args:
  227. head_components: The components to include in the head.
  228. Returns:
  229. The path and code of the compiled document root.
  230. """
  231. # Get the path for the output file.
  232. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  233. # Create the document root.
  234. document_root = utils.create_document_root(head_components)
  235. # Compile the document root.
  236. code = _compile_document_root(document_root)
  237. return output_path, code
  238. def compile_app(app_root: Component) -> tuple[str, str]:
  239. """Compile the app root.
  240. Args:
  241. app_root: The app root component to compile.
  242. Returns:
  243. The path and code of the compiled app wrapper.
  244. """
  245. # Get the path for the output file.
  246. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  247. # Compile the document root.
  248. code = _compile_app(app_root)
  249. return output_path, code
  250. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  251. """Compile the theme.
  252. Args:
  253. style: The style to compile.
  254. Returns:
  255. The path and code of the compiled theme.
  256. """
  257. output_path = utils.get_theme_path()
  258. # Create the theme.
  259. theme = utils.create_theme(style)
  260. # Compile the theme.
  261. code = _compile_theme(theme)
  262. return output_path, code
  263. def compile_contexts(state: Optional[Type[State]]) -> tuple[str, str]:
  264. """Compile the initial state / context.
  265. Args:
  266. state: The app state.
  267. Returns:
  268. The path and code of the compiled context.
  269. """
  270. # Get the path for the output file.
  271. output_path = utils.get_context_path()
  272. return output_path, _compile_contexts(state)
  273. def compile_page(
  274. path: str, component: Component, state: Type[State]
  275. ) -> tuple[str, str]:
  276. """Compile a single page.
  277. Args:
  278. path: The path to compile the page to.
  279. component: The component to compile.
  280. state: The app state.
  281. Returns:
  282. The path and code of the compiled page.
  283. """
  284. # Get the path for the output file.
  285. output_path = utils.get_page_path(path)
  286. # Add the style to the component.
  287. code = _compile_page(component, state)
  288. return output_path, code
  289. def compile_components(components: set[CustomComponent]):
  290. """Compile the custom components.
  291. Args:
  292. components: The custom components to compile.
  293. Returns:
  294. The path and code of the compiled components.
  295. """
  296. # Get the path for the output file.
  297. output_path = utils.get_components_path()
  298. # Compile the components.
  299. code = _compile_components(components)
  300. return output_path, code
  301. def compile_stateful_components(
  302. pages: Iterable[Component],
  303. ) -> tuple[str, str, list[BaseComponent]]:
  304. """Separately compile components that depend on State vars.
  305. StatefulComponents are compiled as their own component functions with their own
  306. useContext declarations, which allows page components to be stateless and avoid
  307. re-rendering along with parts of the page that actually depend on state.
  308. Args:
  309. pages: The pages to extract stateful components from.
  310. Returns:
  311. The path and code of the compiled stateful components.
  312. """
  313. output_path = utils.get_stateful_components_path()
  314. # Compile the stateful components.
  315. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  316. code = _compile_stateful_components(page_components)
  317. return output_path, code, page_components
  318. def compile_tailwind(
  319. config: dict,
  320. ):
  321. """Compile the Tailwind config.
  322. Args:
  323. config: The Tailwind config.
  324. Returns:
  325. The compiled Tailwind config.
  326. """
  327. # Get the path for the output file.
  328. output_path = constants.Tailwind.CONFIG
  329. # Compile the config.
  330. code = _compile_tailwind(config)
  331. return output_path, code
  332. def purge_web_pages_dir():
  333. """Empty out .web directory."""
  334. utils.empty_dir(constants.Dirs.WEB_PAGES, keep_files=["_app.js"])