compiler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. import os
  4. from datetime import datetime
  5. from pathlib import Path
  6. from typing import Dict, Iterable, Optional, Type, Union
  7. from reflex import constants
  8. from reflex.compiler import templates, utils
  9. from reflex.components.component import (
  10. BaseComponent,
  11. Component,
  12. ComponentStyle,
  13. CustomComponent,
  14. StatefulComponent,
  15. )
  16. from reflex.config import get_config
  17. from reflex.state import BaseState
  18. from reflex.style import SYSTEM_COLOR_MODE
  19. from reflex.utils.exec import is_prod_mode
  20. from reflex.utils.imports import ImportVar
  21. from reflex.utils.prerequisites import get_web_dir
  22. from reflex.vars import Var
  23. def _compile_document_root(root: Component) -> str:
  24. """Compile the document root.
  25. Args:
  26. root: The document root to compile.
  27. Returns:
  28. The compiled document root.
  29. """
  30. return templates.DOCUMENT_ROOT.render(
  31. imports=utils.compile_imports(root._get_all_imports()),
  32. document=root.render(),
  33. )
  34. def _compile_app(app_root: Component) -> str:
  35. """Compile the app template component.
  36. Args:
  37. app_root: The app root to compile.
  38. Returns:
  39. The compiled app.
  40. """
  41. return templates.APP_ROOT.render(
  42. imports=utils.compile_imports(app_root._get_all_imports()),
  43. custom_codes=app_root._get_all_custom_code(),
  44. hooks={**app_root._get_all_hooks_internal(), **app_root._get_all_hooks()},
  45. render=app_root.render(),
  46. )
  47. def _compile_theme(theme: dict) -> str:
  48. """Compile the theme.
  49. Args:
  50. theme: The theme to compile.
  51. Returns:
  52. The compiled theme.
  53. """
  54. return templates.THEME.render(theme=theme)
  55. def _compile_contexts(state: Optional[Type[BaseState]], theme: Component | None) -> str:
  56. """Compile the initial state and contexts.
  57. Args:
  58. state: The app state.
  59. theme: The top-level app theme.
  60. Returns:
  61. The compiled context file.
  62. """
  63. appearance = getattr(theme, "appearance", None)
  64. if appearance is None or Var.create_safe(appearance)._var_name == "inherit":
  65. appearance = SYSTEM_COLOR_MODE
  66. last_compiled_time = str(datetime.now())
  67. return (
  68. templates.CONTEXT.render(
  69. initial_state=utils.compile_state(state),
  70. state_name=state.get_name(),
  71. client_storage=utils.compile_client_storage(state),
  72. is_dev_mode=not is_prod_mode(),
  73. last_compiled_time=last_compiled_time,
  74. default_color_mode=appearance,
  75. )
  76. if state
  77. else templates.CONTEXT.render(
  78. is_dev_mode=not is_prod_mode(),
  79. default_color_mode=appearance,
  80. last_compiled_time=last_compiled_time,
  81. )
  82. )
  83. def _compile_page(
  84. component: Component,
  85. state: Type[BaseState],
  86. ) -> str:
  87. """Compile the component given the app state.
  88. Args:
  89. component: The component to compile.
  90. state: The app state.
  91. Returns:
  92. The compiled component.
  93. """
  94. imports = component._get_all_imports()
  95. imports = utils.compile_imports(imports)
  96. # Compile the code to render the component.
  97. kwargs = {"state_name": state.get_name()} if state else {}
  98. return templates.PAGE.render(
  99. imports=imports,
  100. dynamic_imports=component._get_all_dynamic_imports(),
  101. custom_codes=component._get_all_custom_code(),
  102. hooks={**component._get_all_hooks_internal(), **component._get_all_hooks()},
  103. render=component.render(),
  104. **kwargs,
  105. )
  106. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  107. """Compile the root stylesheet.
  108. Args:
  109. stylesheets: The stylesheets to include in the root stylesheet.
  110. Returns:
  111. The path and code of the compiled root stylesheet.
  112. """
  113. output_path = utils.get_root_stylesheet_path()
  114. code = _compile_root_stylesheet(stylesheets)
  115. return output_path, code
  116. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  117. """Compile the root stylesheet.
  118. Args:
  119. stylesheets: The stylesheets to include in the root stylesheet.
  120. Returns:
  121. The compiled root stylesheet.
  122. Raises:
  123. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  124. """
  125. # Add tailwind css if enabled.
  126. sheets = (
  127. [constants.Tailwind.ROOT_STYLE_PATH]
  128. if get_config().tailwind is not None
  129. else []
  130. )
  131. for stylesheet in stylesheets:
  132. if not utils.is_valid_url(stylesheet):
  133. # check if stylesheet provided exists.
  134. stylesheet_full_path = (
  135. Path.cwd() / constants.Dirs.APP_ASSETS / stylesheet.strip("/")
  136. )
  137. if not os.path.exists(stylesheet_full_path):
  138. raise FileNotFoundError(
  139. f"The stylesheet file {stylesheet_full_path} does not exist."
  140. )
  141. stylesheet = f"../{constants.Dirs.PUBLIC}/{stylesheet.strip('/')}"
  142. sheets.append(stylesheet) if stylesheet not in sheets else None
  143. return templates.STYLE.render(stylesheets=sheets)
  144. def _compile_component(component: Component | StatefulComponent) -> str:
  145. """Compile a single component.
  146. Args:
  147. component: The component to compile.
  148. Returns:
  149. The compiled component.
  150. """
  151. return templates.COMPONENT.render(component=component)
  152. def _compile_components(
  153. components: set[CustomComponent],
  154. ) -> tuple[str, Dict[str, list[ImportVar]]]:
  155. """Compile the components.
  156. Args:
  157. components: The components to compile.
  158. Returns:
  159. The compiled components.
  160. """
  161. imports = {
  162. "react": [ImportVar(tag="memo")],
  163. f"/{constants.Dirs.STATE_PATH}": [ImportVar(tag="E"), ImportVar(tag="isTrue")],
  164. }
  165. component_renders = []
  166. # Compile each component.
  167. for component in components:
  168. component_render, component_imports = utils.compile_custom_component(component)
  169. component_renders.append(component_render)
  170. imports = utils.merge_imports(imports, component_imports)
  171. # Compile the components page.
  172. return (
  173. templates.COMPONENTS.render(
  174. imports=utils.compile_imports(imports),
  175. components=component_renders,
  176. ),
  177. imports,
  178. )
  179. def _compile_stateful_components(
  180. page_components: list[BaseComponent],
  181. ) -> str:
  182. """Walk the page components and extract shared stateful components.
  183. Any StatefulComponent that is shared by more than one page will be rendered
  184. to a separate module and marked rendered_as_shared so subsequent
  185. renderings will import the component from the shared module instead of
  186. directly including the code for it.
  187. Args:
  188. page_components: The Components or StatefulComponents to compile.
  189. Returns:
  190. The rendered stateful components code.
  191. """
  192. all_import_dicts = []
  193. rendered_components = {}
  194. def get_shared_components_recursive(component: BaseComponent):
  195. """Get the shared components for a component and its children.
  196. A shared component is a StatefulComponent that appears in 2 or more
  197. pages and is a candidate for writing to a common file and importing
  198. into each page where it is used.
  199. Args:
  200. component: The component to collect shared StatefulComponents for.
  201. """
  202. for child in component.children:
  203. # Depth-first traversal.
  204. get_shared_components_recursive(child)
  205. # When the component is referenced by more than one page, render it
  206. # to be included in the STATEFUL_COMPONENTS module.
  207. # Skip this step in dev mode, thereby avoiding potential hot reload errors for larger apps
  208. if (
  209. isinstance(component, StatefulComponent)
  210. and component.references > 1
  211. and is_prod_mode()
  212. ):
  213. # Reset this flag to render the actual component.
  214. component.rendered_as_shared = False
  215. # Include dynamic imports in the shared component.
  216. if dynamic_imports := component._get_all_dynamic_imports():
  217. rendered_components.update(
  218. {dynamic_import: None for dynamic_import in dynamic_imports}
  219. )
  220. # Include custom code in the shared component.
  221. rendered_components.update(
  222. {code: None for code in component._get_all_custom_code()},
  223. )
  224. # Include all imports in the shared component.
  225. all_import_dicts.append(component._get_all_imports())
  226. # Indicate that this component now imports from the shared file.
  227. component.rendered_as_shared = True
  228. for page_component in page_components:
  229. get_shared_components_recursive(page_component)
  230. # Don't import from the file that we're about to create.
  231. all_imports = utils.merge_imports(*all_import_dicts)
  232. all_imports.pop(
  233. f"/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
  234. )
  235. return templates.STATEFUL_COMPONENTS.render(
  236. imports=utils.compile_imports(all_imports),
  237. memoized_code="\n".join(rendered_components),
  238. )
  239. def _compile_tailwind(
  240. config: dict,
  241. ) -> str:
  242. """Compile the Tailwind config.
  243. Args:
  244. config: The Tailwind config.
  245. Returns:
  246. The compiled Tailwind config.
  247. """
  248. return templates.TAILWIND_CONFIG.render(
  249. **config,
  250. )
  251. def compile_document_root(
  252. head_components: list[Component],
  253. html_lang: Optional[str] = None,
  254. html_custom_attrs: Optional[Dict[str, Union[Var, str]]] = None,
  255. ) -> tuple[str, str]:
  256. """Compile the document root.
  257. Args:
  258. head_components: The components to include in the head.
  259. html_lang: The language of the document, will be added to the html root element.
  260. html_custom_attrs: custom attributes added to the html root element.
  261. Returns:
  262. The path and code of the compiled document root.
  263. """
  264. # Get the path for the output file.
  265. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  266. # Create the document root.
  267. document_root = utils.create_document_root(
  268. head_components, html_lang=html_lang, html_custom_attrs=html_custom_attrs
  269. )
  270. # Compile the document root.
  271. code = _compile_document_root(document_root)
  272. return output_path, code
  273. def compile_app(app_root: Component) -> tuple[str, str]:
  274. """Compile the app root.
  275. Args:
  276. app_root: The app root component to compile.
  277. Returns:
  278. The path and code of the compiled app wrapper.
  279. """
  280. # Get the path for the output file.
  281. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  282. # Compile the document root.
  283. code = _compile_app(app_root)
  284. return output_path, code
  285. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  286. """Compile the theme.
  287. Args:
  288. style: The style to compile.
  289. Returns:
  290. The path and code of the compiled theme.
  291. """
  292. output_path = utils.get_theme_path()
  293. # Create the theme.
  294. theme = utils.create_theme(style)
  295. # Compile the theme.
  296. code = _compile_theme(theme)
  297. return output_path, code
  298. def compile_contexts(
  299. state: Optional[Type[BaseState]],
  300. theme: Component | None,
  301. ) -> tuple[str, str]:
  302. """Compile the initial state / context.
  303. Args:
  304. state: The app state.
  305. theme: The top-level app theme.
  306. Returns:
  307. The path and code of the compiled context.
  308. """
  309. # Get the path for the output file.
  310. output_path = utils.get_context_path()
  311. return output_path, _compile_contexts(state, theme)
  312. def compile_page(
  313. path: str, component: Component, state: Type[BaseState]
  314. ) -> tuple[str, str]:
  315. """Compile a single page.
  316. Args:
  317. path: The path to compile the page to.
  318. component: The component to compile.
  319. state: The app state.
  320. Returns:
  321. The path and code of the compiled page.
  322. """
  323. # Get the path for the output file.
  324. output_path = utils.get_page_path(path)
  325. # Add the style to the component.
  326. code = _compile_page(component, state)
  327. return output_path, code
  328. def compile_components(
  329. components: set[CustomComponent],
  330. ) -> tuple[str, str, Dict[str, list[ImportVar]]]:
  331. """Compile the custom components.
  332. Args:
  333. components: The custom components to compile.
  334. Returns:
  335. The path and code of the compiled components.
  336. """
  337. # Get the path for the output file.
  338. output_path = utils.get_components_path()
  339. # Compile the components.
  340. code, imports = _compile_components(components)
  341. return output_path, code, imports
  342. def compile_stateful_components(
  343. pages: Iterable[Component],
  344. ) -> tuple[str, str, list[BaseComponent]]:
  345. """Separately compile components that depend on State vars.
  346. StatefulComponents are compiled as their own component functions with their own
  347. useContext declarations, which allows page components to be stateless and avoid
  348. re-rendering along with parts of the page that actually depend on state.
  349. Args:
  350. pages: The pages to extract stateful components from.
  351. Returns:
  352. The path and code of the compiled stateful components.
  353. """
  354. output_path = utils.get_stateful_components_path()
  355. # Compile the stateful components.
  356. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  357. code = _compile_stateful_components(page_components)
  358. return output_path, code, page_components
  359. def compile_tailwind(
  360. config: dict,
  361. ):
  362. """Compile the Tailwind config.
  363. Args:
  364. config: The Tailwind config.
  365. Returns:
  366. The compiled Tailwind config.
  367. """
  368. # Get the path for the output file.
  369. output_path = get_web_dir() / constants.Tailwind.CONFIG
  370. # Compile the config.
  371. code = _compile_tailwind(config)
  372. return output_path, code
  373. def remove_tailwind_from_postcss() -> tuple[str, str]:
  374. """If tailwind is not to be used, remove it from postcss.config.js.
  375. Returns:
  376. The path and code of the compiled postcss.config.js.
  377. """
  378. # Get the path for the output file.
  379. output_path = str(get_web_dir() / constants.Dirs.POSTCSS_JS)
  380. code = [
  381. line
  382. for line in Path(output_path).read_text().splitlines(keepends=True)
  383. if "tailwindcss: " not in line
  384. ]
  385. # Compile the config.
  386. return output_path, "".join(code)
  387. def purge_web_pages_dir():
  388. """Empty out .web/pages directory."""
  389. if not is_prod_mode() and os.environ.get("REFLEX_PERSIST_WEB_DIR"):
  390. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
  391. return
  392. # Empty out the web pages directory.
  393. utils.empty_dir(get_web_dir() / constants.Dirs.PAGES, keep_files=["_app.js"])
  394. class ExecutorSafeFunctions:
  395. """Helper class to allow parallelisation of parts of the compilation process.
  396. This class (and its class attributes) are available at global scope.
  397. In a multiprocessing context (like when using a ProcessPoolExecutor), the content of this
  398. global class is logically replicated to any FORKED process.
  399. How it works:
  400. * Before the child process is forked, ensure that we stash any input data required by any future
  401. function call in the child process.
  402. * After the child process is forked, the child process will have a copy of the global class, which
  403. includes the previously stashed input data.
  404. * Any task submitted to the child process simply needs a way to communicate which input data the
  405. requested function call requires.
  406. Why do we need this? Passing input data directly to child process often not possible because the input data is not picklable.
  407. The mechanic described here removes the need to pickle the input data at all.
  408. Limitations:
  409. * This can never support returning unpicklable OUTPUT data.
  410. * Any object mutations done by the child process will not propagate back to the parent process (fork goes one way!).
  411. """
  412. COMPILE_PAGE_ARGS_BY_ROUTE = {}
  413. COMPILE_APP_APP_ROOT: Component | None = None
  414. CUSTOM_COMPONENTS: set[CustomComponent] | None = None
  415. STYLE: ComponentStyle | None = None
  416. @classmethod
  417. def compile_page(cls, route: str):
  418. """Compile a page.
  419. Args:
  420. route: The route of the page to compile.
  421. Returns:
  422. The path and code of the compiled page.
  423. """
  424. return compile_page(*cls.COMPILE_PAGE_ARGS_BY_ROUTE[route])
  425. @classmethod
  426. def compile_app(cls):
  427. """Compile the app.
  428. Returns:
  429. The path and code of the compiled app.
  430. Raises:
  431. ValueError: If the app root is not set.
  432. """
  433. if cls.COMPILE_APP_APP_ROOT is None:
  434. raise ValueError("COMPILE_APP_APP_ROOT should be set")
  435. return compile_app(cls.COMPILE_APP_APP_ROOT)
  436. @classmethod
  437. def compile_custom_components(cls):
  438. """Compile the custom components.
  439. Returns:
  440. The path and code of the compiled custom components.
  441. Raises:
  442. ValueError: If the custom components are not set.
  443. """
  444. if cls.CUSTOM_COMPONENTS is None:
  445. raise ValueError("CUSTOM_COMPONENTS should be set")
  446. return compile_components(cls.CUSTOM_COMPONENTS)
  447. @classmethod
  448. def compile_theme(cls):
  449. """Compile the theme.
  450. Returns:
  451. The path and code of the compiled theme.
  452. Raises:
  453. ValueError: If the style is not set.
  454. """
  455. if cls.STYLE is None:
  456. raise ValueError("STYLE should be set")
  457. return compile_theme(cls.STYLE)