compiler.py 27 KB

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