1
0

compiler.py 21 KB

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