1
0

compiler.py 28 KB

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