compiler.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. from collections.abc import Iterable, Sequence
  4. from datetime import datetime
  5. from inspect import getmodule
  6. from pathlib import Path
  7. from typing import TYPE_CHECKING
  8. from reflex import constants
  9. from reflex.compiler import templates, utils
  10. from reflex.components.base.fragment import Fragment
  11. from reflex.components.component import (
  12. BaseComponent,
  13. Component,
  14. ComponentStyle,
  15. CustomComponent,
  16. StatefulComponent,
  17. )
  18. from reflex.config import environment, get_config
  19. from reflex.constants.compiler import PageNames
  20. from reflex.state import BaseState
  21. from reflex.style import SYSTEM_COLOR_MODE
  22. from reflex.utils import console, path_ops
  23. from reflex.utils.exceptions import ReflexError
  24. from reflex.utils.exec import is_prod_mode
  25. from reflex.utils.imports import ImportVar
  26. from reflex.utils.prerequisites import get_web_dir
  27. from reflex.vars.base import LiteralVar, Var
  28. def _compile_document_root(root: Component) -> str:
  29. """Compile the document root.
  30. Args:
  31. root: The document root to compile.
  32. Returns:
  33. The compiled document root.
  34. """
  35. return templates.DOCUMENT_ROOT.render(
  36. imports=utils.compile_imports(root._get_all_imports()),
  37. document=root.render(),
  38. )
  39. def _normalize_library_name(lib: str) -> str:
  40. """Normalize the library name.
  41. Args:
  42. lib: The library name to normalize.
  43. Returns:
  44. The normalized library name.
  45. """
  46. if lib == "react":
  47. return "React"
  48. return lib.replace("@", "").replace("/", "_").replace("-", "_")
  49. def _compile_app(app_root: Component) -> str:
  50. """Compile the app template component.
  51. Args:
  52. app_root: The app root to compile.
  53. Returns:
  54. The compiled app.
  55. """
  56. from reflex.components.dynamic import bundled_libraries
  57. window_libraries = [
  58. (_normalize_library_name(name), name) for name in bundled_libraries
  59. ] + [
  60. ("utils_context", f"$/{constants.Dirs.UTILS}/context"),
  61. ("utils_state", f"$/{constants.Dirs.UTILS}/state"),
  62. ]
  63. return templates.APP_ROOT.render(
  64. imports=utils.compile_imports(app_root._get_all_imports()),
  65. custom_codes=app_root._get_all_custom_code(),
  66. hooks=app_root._get_all_hooks(),
  67. window_libraries=window_libraries,
  68. render=app_root.render(),
  69. dynamic_imports=app_root._get_all_dynamic_imports(),
  70. )
  71. def _compile_theme(theme: str) -> str:
  72. """Compile the theme.
  73. Args:
  74. theme: The theme to compile.
  75. Returns:
  76. The compiled theme.
  77. """
  78. return templates.THEME.render(theme=theme)
  79. def _compile_contexts(state: type[BaseState] | None, theme: Component | None) -> str:
  80. """Compile the initial state and contexts.
  81. Args:
  82. state: The app state.
  83. theme: The top-level app theme.
  84. Returns:
  85. The compiled context file.
  86. """
  87. appearance = getattr(theme, "appearance", None)
  88. if appearance is None or str(LiteralVar.create(appearance)) == '"inherit"':
  89. appearance = LiteralVar.create(SYSTEM_COLOR_MODE)
  90. last_compiled_time = str(datetime.now())
  91. return (
  92. templates.CONTEXT.render(
  93. initial_state=utils.compile_state(state),
  94. state_name=state.get_name(),
  95. client_storage=utils.compile_client_storage(state),
  96. is_dev_mode=not is_prod_mode(),
  97. last_compiled_time=last_compiled_time,
  98. default_color_mode=appearance,
  99. )
  100. if state
  101. else templates.CONTEXT.render(
  102. is_dev_mode=not is_prod_mode(),
  103. default_color_mode=appearance,
  104. last_compiled_time=last_compiled_time,
  105. )
  106. )
  107. def _compile_page(
  108. component: BaseComponent,
  109. state: type[BaseState] | None,
  110. ) -> str:
  111. """Compile the component given the app state.
  112. Args:
  113. component: The component to compile.
  114. state: The app state.
  115. Returns:
  116. The compiled component.
  117. """
  118. imports = component._get_all_imports()
  119. imports = utils.compile_imports(imports)
  120. # Compile the code to render the component.
  121. kwargs = {"state_name": state.get_name()} if state is not None else {}
  122. return templates.PAGE.render(
  123. imports=imports,
  124. dynamic_imports=component._get_all_dynamic_imports(),
  125. custom_codes=component._get_all_custom_code(),
  126. hooks=component._get_all_hooks(),
  127. render=component.render(),
  128. **kwargs,
  129. )
  130. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  131. """Compile the root stylesheet.
  132. Args:
  133. stylesheets: The stylesheets to include in the root stylesheet.
  134. Returns:
  135. The path and code of the compiled root stylesheet.
  136. """
  137. output_path = utils.get_root_stylesheet_path()
  138. code = _compile_root_stylesheet(stylesheets)
  139. return output_path, code
  140. def _validate_stylesheet(stylesheet_full_path: Path, assets_app_path: Path) -> None:
  141. """Validate the stylesheet.
  142. Args:
  143. stylesheet_full_path: The stylesheet to validate.
  144. assets_app_path: The path to the assets directory.
  145. Raises:
  146. ValueError: If the stylesheet is not supported.
  147. FileNotFoundError: If the stylesheet is not found.
  148. """
  149. suffix = stylesheet_full_path.suffix[1:] if stylesheet_full_path.suffix else ""
  150. if suffix not in constants.Reflex.STYLESHEETS_SUPPORTED:
  151. raise ValueError(f"Stylesheet file {stylesheet_full_path} is not supported.")
  152. if not stylesheet_full_path.absolute().is_relative_to(assets_app_path.absolute()):
  153. raise FileNotFoundError(
  154. f"Cannot include stylesheets from outside the assets directory: {stylesheet_full_path}"
  155. )
  156. if not stylesheet_full_path.name:
  157. raise ValueError(
  158. f"Stylesheet file name cannot be empty: {stylesheet_full_path}"
  159. )
  160. if (
  161. len(
  162. stylesheet_full_path.absolute()
  163. .relative_to(assets_app_path.absolute())
  164. .parts
  165. )
  166. == 1
  167. and stylesheet_full_path.stem == PageNames.STYLESHEET_ROOT
  168. ):
  169. raise ValueError(
  170. f"Stylesheet file name cannot be '{PageNames.STYLESHEET_ROOT}': {stylesheet_full_path}"
  171. )
  172. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  173. """Compile the root stylesheet.
  174. Args:
  175. stylesheets: The stylesheets to include in the root stylesheet.
  176. Returns:
  177. The compiled root stylesheet.
  178. Raises:
  179. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  180. """
  181. # Add stylesheets from plugins.
  182. sheets = [
  183. sheet
  184. for plugin in get_config().plugins
  185. for sheet in plugin.get_stylesheet_paths()
  186. ] + ["@radix-ui/themes/styles.css"]
  187. failed_to_import_sass = False
  188. assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS
  189. stylesheets_files: list[Path] = []
  190. stylesheets_urls = []
  191. for stylesheet in stylesheets:
  192. if not utils.is_valid_url(stylesheet):
  193. # check if stylesheet provided exists.
  194. stylesheet_full_path = assets_app_path / stylesheet.strip("/")
  195. if not stylesheet_full_path.exists():
  196. raise FileNotFoundError(
  197. f"The stylesheet file {stylesheet_full_path} does not exist."
  198. )
  199. if stylesheet_full_path.is_dir():
  200. all_files = (
  201. file
  202. for ext in constants.Reflex.STYLESHEETS_SUPPORTED
  203. for file in stylesheet_full_path.rglob("*." + ext)
  204. )
  205. for file in all_files:
  206. if file.is_dir():
  207. continue
  208. # Validate the stylesheet.
  209. _validate_stylesheet(file, assets_app_path)
  210. stylesheets_files.append(file)
  211. else:
  212. # Validate the stylesheet.
  213. _validate_stylesheet(stylesheet_full_path, assets_app_path)
  214. stylesheets_files.append(stylesheet_full_path)
  215. else:
  216. stylesheets_urls.append(stylesheet)
  217. sheets.extend(dict.fromkeys(stylesheets_urls))
  218. for stylesheet in stylesheets_files:
  219. target_path = stylesheet.relative_to(assets_app_path).with_suffix(".css")
  220. target = get_web_dir() / constants.Dirs.STYLES / target_path
  221. target.parent.mkdir(parents=True, exist_ok=True)
  222. if stylesheet.suffix == ".css":
  223. path_ops.cp(src=stylesheet, dest=target, overwrite=True)
  224. else:
  225. try:
  226. from sass import compile as sass_compile
  227. target.write_text(
  228. data=sass_compile(
  229. filename=str(stylesheet),
  230. output_style="compressed",
  231. ),
  232. encoding="utf8",
  233. )
  234. except ImportError:
  235. failed_to_import_sass = True
  236. str_target_path = "./" + str(target_path)
  237. sheets.append(str_target_path) if str_target_path not in sheets else None
  238. if failed_to_import_sass:
  239. console.error(
  240. 'The `libsass` package is required to compile sass/scss stylesheet files. Run `pip install "libsass>=0.23.0"`.'
  241. )
  242. return templates.STYLE.render(stylesheets=sheets)
  243. def _compile_component(component: Component | StatefulComponent) -> str:
  244. """Compile a single component.
  245. Args:
  246. component: The component to compile.
  247. Returns:
  248. The compiled component.
  249. """
  250. return templates.COMPONENT.render(component=component)
  251. def _compile_components(
  252. components: set[CustomComponent],
  253. ) -> tuple[str, dict[str, list[ImportVar]]]:
  254. """Compile the components.
  255. Args:
  256. components: The components to compile.
  257. Returns:
  258. The compiled components.
  259. """
  260. imports = {
  261. "react": [ImportVar(tag="memo")],
  262. f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="E"), ImportVar(tag="isTrue")],
  263. }
  264. component_renders = []
  265. # Compile each component.
  266. for component in components:
  267. component_render, component_imports = utils.compile_custom_component(component)
  268. component_renders.append(component_render)
  269. imports = utils.merge_imports(imports, component_imports)
  270. dynamic_imports = {
  271. comp_import: None
  272. for comp_render in component_renders
  273. if "dynamic_imports" in comp_render
  274. for comp_import in comp_render["dynamic_imports"]
  275. }
  276. custom_codes = {
  277. comp_custom_code: None
  278. for comp_render in component_renders
  279. for comp_custom_code in comp_render.get("custom_code", [])
  280. }
  281. # Compile the components page.
  282. return (
  283. templates.COMPONENTS.render(
  284. imports=utils.compile_imports(imports),
  285. components=component_renders,
  286. dynamic_imports=dynamic_imports,
  287. custom_codes=custom_codes,
  288. ),
  289. imports,
  290. )
  291. def _compile_stateful_components(
  292. page_components: list[BaseComponent],
  293. ) -> str:
  294. """Walk the page components and extract shared stateful components.
  295. Any StatefulComponent that is shared by more than one page will be rendered
  296. to a separate module and marked rendered_as_shared so subsequent
  297. renderings will import the component from the shared module instead of
  298. directly including the code for it.
  299. Args:
  300. page_components: The Components or StatefulComponents to compile.
  301. Returns:
  302. The rendered stateful components code.
  303. """
  304. all_import_dicts = []
  305. rendered_components = {}
  306. def get_shared_components_recursive(component: BaseComponent):
  307. """Get the shared components for a component and its children.
  308. A shared component is a StatefulComponent that appears in 2 or more
  309. pages and is a candidate for writing to a common file and importing
  310. into each page where it is used.
  311. Args:
  312. component: The component to collect shared StatefulComponents for.
  313. """
  314. for child in component.children:
  315. # Depth-first traversal.
  316. get_shared_components_recursive(child)
  317. # When the component is referenced by more than one page, render it
  318. # to be included in the STATEFUL_COMPONENTS module.
  319. # Skip this step in dev mode, thereby avoiding potential hot reload errors for larger apps
  320. if (
  321. isinstance(component, StatefulComponent)
  322. and component.references > 1
  323. and is_prod_mode()
  324. ):
  325. # Reset this flag to render the actual component.
  326. component.rendered_as_shared = False
  327. # Include dynamic imports in the shared component.
  328. if dynamic_imports := component._get_all_dynamic_imports():
  329. rendered_components.update(dict.fromkeys(dynamic_imports))
  330. # Include custom code in the shared component.
  331. rendered_components.update(
  332. dict.fromkeys(component._get_all_custom_code()),
  333. )
  334. # Include all imports in the shared component.
  335. all_import_dicts.append(component._get_all_imports())
  336. # Indicate that this component now imports from the shared file.
  337. component.rendered_as_shared = True
  338. for page_component in page_components:
  339. get_shared_components_recursive(page_component)
  340. # Don't import from the file that we're about to create.
  341. all_imports = utils.merge_imports(*all_import_dicts)
  342. all_imports.pop(
  343. f"$/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
  344. )
  345. return templates.STATEFUL_COMPONENTS.render(
  346. imports=utils.compile_imports(all_imports),
  347. memoized_code="\n".join(rendered_components),
  348. )
  349. def compile_document_root(
  350. head_components: list[Component],
  351. html_lang: str | None = None,
  352. html_custom_attrs: dict[str, Var | str] | None = None,
  353. ) -> tuple[str, str]:
  354. """Compile the document root.
  355. Args:
  356. head_components: The components to include in the head.
  357. html_lang: The language of the document, will be added to the html root element.
  358. html_custom_attrs: custom attributes added to the html root element.
  359. Returns:
  360. The path and code of the compiled document root.
  361. """
  362. # Get the path for the output file.
  363. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  364. # Create the document root.
  365. document_root = utils.create_document_root(
  366. head_components, html_lang=html_lang, html_custom_attrs=html_custom_attrs
  367. )
  368. # Compile the document root.
  369. code = _compile_document_root(document_root)
  370. return output_path, code
  371. def compile_app(app_root: Component) -> tuple[str, str]:
  372. """Compile the app root.
  373. Args:
  374. app_root: The app root component to compile.
  375. Returns:
  376. The path and code of the compiled app wrapper.
  377. """
  378. # Get the path for the output file.
  379. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  380. # Compile the document root.
  381. code = _compile_app(app_root)
  382. return output_path, code
  383. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  384. """Compile the theme.
  385. Args:
  386. style: The style to compile.
  387. Returns:
  388. The path and code of the compiled theme.
  389. """
  390. output_path = utils.get_theme_path()
  391. # Create the theme.
  392. theme = utils.create_theme(style)
  393. # Compile the theme.
  394. code = _compile_theme(str(LiteralVar.create(theme)))
  395. return output_path, code
  396. def compile_contexts(
  397. state: type[BaseState] | None,
  398. theme: Component | None,
  399. ) -> tuple[str, str]:
  400. """Compile the initial state / context.
  401. Args:
  402. state: The app state.
  403. theme: The top-level app theme.
  404. Returns:
  405. The path and code of the compiled context.
  406. """
  407. # Get the path for the output file.
  408. output_path = utils.get_context_path()
  409. return output_path, _compile_contexts(state, theme)
  410. def compile_page(
  411. path: str, component: BaseComponent, state: type[BaseState] | None
  412. ) -> tuple[str, str]:
  413. """Compile a single page.
  414. Args:
  415. path: The path to compile the page to.
  416. component: The component to compile.
  417. state: The app state.
  418. Returns:
  419. The path and code of the compiled page.
  420. """
  421. # Get the path for the output file.
  422. output_path = utils.get_page_path(path)
  423. # Add the style to the component.
  424. code = _compile_page(component, state)
  425. return output_path, code
  426. def compile_components(
  427. components: set[CustomComponent],
  428. ) -> tuple[str, str, dict[str, list[ImportVar]]]:
  429. """Compile the custom components.
  430. Args:
  431. components: The custom components to compile.
  432. Returns:
  433. The path and code of the compiled components.
  434. """
  435. # Get the path for the output file.
  436. output_path = utils.get_components_path()
  437. # Compile the components.
  438. code, imports = _compile_components(components)
  439. return output_path, code, imports
  440. def compile_stateful_components(
  441. pages: Iterable[Component],
  442. ) -> tuple[str, str, list[BaseComponent]]:
  443. """Separately compile components that depend on State vars.
  444. StatefulComponents are compiled as their own component functions with their own
  445. useContext declarations, which allows page components to be stateless and avoid
  446. re-rendering along with parts of the page that actually depend on state.
  447. Args:
  448. pages: The pages to extract stateful components from.
  449. Returns:
  450. The path and code of the compiled stateful components.
  451. """
  452. output_path = utils.get_stateful_components_path()
  453. # Compile the stateful components.
  454. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  455. code = _compile_stateful_components(page_components)
  456. return output_path, code, page_components
  457. def purge_web_pages_dir():
  458. """Empty out .web/pages directory."""
  459. if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR.get():
  460. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
  461. return
  462. # Empty out the web pages directory.
  463. utils.empty_dir(get_web_dir() / constants.Dirs.PAGES, keep_files=["_app.js"])
  464. if TYPE_CHECKING:
  465. from reflex.app import ComponentCallable, UnevaluatedPage
  466. def _into_component_once(
  467. component: Component
  468. | ComponentCallable
  469. | tuple[Component, ...]
  470. | str
  471. | Var
  472. | int
  473. | float,
  474. ) -> Component | None:
  475. """Convert a component to a Component.
  476. Args:
  477. component: The component to convert.
  478. Returns:
  479. The converted component.
  480. """
  481. if isinstance(component, Component):
  482. return component
  483. if isinstance(component, (Var, int, float, str)):
  484. return Fragment.create(component)
  485. if isinstance(component, Sequence):
  486. return Fragment.create(*component)
  487. return None
  488. def readable_name_from_component(
  489. component: Component | ComponentCallable,
  490. ) -> str | None:
  491. """Get the readable name of a component.
  492. Args:
  493. component: The component to get the name of.
  494. Returns:
  495. The readable name of the component.
  496. """
  497. if isinstance(component, Component):
  498. return type(component).__name__
  499. if isinstance(component, (Var, int, float, str)):
  500. return str(component)
  501. if isinstance(component, Sequence):
  502. return ", ".join(str(c) for c in component)
  503. if callable(component):
  504. module_name = getattr(component, "__module__", None)
  505. if module_name is not None:
  506. module = getmodule(component)
  507. if module is not None:
  508. module_name = module.__name__
  509. if module_name is not None:
  510. return f"{module_name}.{component.__name__}"
  511. return component.__name__
  512. return None
  513. def into_component(component: Component | ComponentCallable) -> Component:
  514. """Convert a component to a Component.
  515. Args:
  516. component: The component to convert.
  517. Returns:
  518. The converted component.
  519. Raises:
  520. TypeError: If the component is not a Component.
  521. # noqa: DAR401
  522. """
  523. if (converted := _into_component_once(component)) is not None:
  524. return converted
  525. try:
  526. if (
  527. callable(component)
  528. and (converted := _into_component_once(component())) is not None
  529. ):
  530. return converted
  531. except KeyError as e:
  532. if isinstance(e, ReflexError):
  533. raise
  534. key = e.args[0] if e.args else None
  535. if key is not None and isinstance(key, Var):
  536. raise TypeError(
  537. "Cannot access a primitive map with a Var. Consider calling rx.Var.create() on the map."
  538. ).with_traceback(e.__traceback__) from None
  539. raise
  540. except TypeError as e:
  541. if isinstance(e, ReflexError):
  542. raise
  543. message = e.args[0] if e.args else None
  544. if message and isinstance(message, str):
  545. if message.endswith("has no len()") and (
  546. "ArrayCastedVar" in message
  547. or "ObjectCastedVar" in message
  548. or "StringCastedVar" in message
  549. ):
  550. raise TypeError(
  551. "Cannot pass a Var to a built-in function. Consider using .length() for accessing the length of an iterable Var."
  552. ).with_traceback(e.__traceback__) from None
  553. if message.endswith(
  554. "indices must be integers or slices, not NumberCastedVar"
  555. ) or message.endswith(
  556. "indices must be integers or slices, not BooleanCastedVar"
  557. ):
  558. raise TypeError(
  559. "Cannot index into a primitive sequence with a Var. Consider calling rx.Var.create() on the sequence."
  560. ).with_traceback(e.__traceback__) from None
  561. if "CastedVar" in str(e):
  562. raise TypeError(
  563. "Cannot pass a Var to a built-in function. Consider moving the operation to the backend, using existing Var operations, or defining a custom Var operation."
  564. ).with_traceback(e.__traceback__) from None
  565. raise
  566. raise TypeError(f"Expected a Component, got {type(component)}")
  567. def compile_unevaluated_page(
  568. route: str,
  569. page: UnevaluatedPage,
  570. state: type[BaseState] | None = None,
  571. style: ComponentStyle | None = None,
  572. theme: Component | None = None,
  573. ) -> tuple[Component, bool]:
  574. """Compiles an uncompiled page into a component and adds meta information.
  575. Args:
  576. route: The route of the page.
  577. page: The uncompiled page object.
  578. state: The state of the app.
  579. style: The style of the page.
  580. theme: The theme of the page.
  581. Returns:
  582. The compiled component and whether state should be enabled.
  583. """
  584. # Generate the component if it is a callable.
  585. component = into_component(page.component)
  586. component._add_style_recursive(style or {}, theme)
  587. enable_state = False
  588. # Ensure state is enabled if this page uses state.
  589. if state is None:
  590. if page.on_load or component._has_stateful_event_triggers():
  591. enable_state = True
  592. else:
  593. for var in component._get_vars(include_children=True):
  594. var_data = var._get_all_var_data()
  595. if not var_data:
  596. continue
  597. if not var_data.state:
  598. continue
  599. enable_state = True
  600. break
  601. from reflex.app import OverlayFragment
  602. from reflex.utils.format import make_default_page_title
  603. component = OverlayFragment.create(component)
  604. meta_args = {
  605. "title": (
  606. page.title
  607. if page.title is not None
  608. else make_default_page_title(get_config().app_name, route)
  609. ),
  610. "image": page.image,
  611. "meta": page.meta,
  612. }
  613. if page.description is not None:
  614. meta_args["description"] = page.description
  615. # Add meta information to the component.
  616. utils.add_meta(
  617. component,
  618. **meta_args,
  619. )
  620. return component, enable_state
  621. class ExecutorSafeFunctions:
  622. """Helper class to allow parallelisation of parts of the compilation process.
  623. This class (and its class attributes) are available at global scope.
  624. In a multiprocessing context (like when using a ProcessPoolExecutor), the content of this
  625. global class is logically replicated to any FORKED process.
  626. How it works:
  627. * Before the child process is forked, ensure that we stash any input data required by any future
  628. function call in the child process.
  629. * After the child process is forked, the child process will have a copy of the global class, which
  630. includes the previously stashed input data.
  631. * Any task submitted to the child process simply needs a way to communicate which input data the
  632. requested function call requires.
  633. Why do we need this? Passing input data directly to child process often not possible because the input data is not picklable.
  634. The mechanic described here removes the need to pickle the input data at all.
  635. Limitations:
  636. * This can never support returning unpicklable OUTPUT data.
  637. * Any object mutations done by the child process will not propagate back to the parent process (fork goes one way!).
  638. """
  639. COMPONENTS: dict[str, BaseComponent] = {}
  640. UNCOMPILED_PAGES: dict[str, UnevaluatedPage] = {}
  641. STATE: type[BaseState] | None = None
  642. @classmethod
  643. def compile_page(cls, route: str) -> tuple[str, str]:
  644. """Compile a page.
  645. Args:
  646. route: The route of the page to compile.
  647. Returns:
  648. The path and code of the compiled page.
  649. """
  650. return compile_page(route, cls.COMPONENTS[route], cls.STATE)
  651. @classmethod
  652. def compile_unevaluated_page(
  653. cls,
  654. route: str,
  655. style: ComponentStyle,
  656. theme: Component | None,
  657. ) -> tuple[str, Component, tuple[str, str]]:
  658. """Compile an unevaluated page.
  659. Args:
  660. route: The route of the page to compile.
  661. style: The style of the page.
  662. theme: The theme of the page.
  663. Returns:
  664. The route, compiled component, and compiled page.
  665. """
  666. component, enable_state = compile_unevaluated_page(
  667. route, cls.UNCOMPILED_PAGES[route], cls.STATE, style, theme
  668. )
  669. return route, component, compile_page(route, component, cls.STATE)
  670. @classmethod
  671. def compile_theme(cls, style: ComponentStyle | None) -> tuple[str, str]:
  672. """Compile the theme.
  673. Args:
  674. style: The style to compile.
  675. Returns:
  676. The path and code of the compiled theme.
  677. Raises:
  678. ValueError: If the style is not set.
  679. """
  680. if style is None:
  681. raise ValueError("STYLE should be set")
  682. return compile_theme(style)