compiler.py 20 KB

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