compiler.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 tailwind css if enabled.
  182. sheets = (
  183. [constants.Tailwind.ROOT_STYLE_PATH]
  184. if get_config().tailwind is not None
  185. else []
  186. )
  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_tailwind(
  350. config: dict,
  351. ) -> str:
  352. """Compile the Tailwind config.
  353. Args:
  354. config: The Tailwind config.
  355. Returns:
  356. The compiled Tailwind config.
  357. """
  358. return templates.TAILWIND_CONFIG.render(
  359. **config,
  360. )
  361. def compile_document_root(
  362. head_components: list[Component],
  363. html_lang: str | None = None,
  364. html_custom_attrs: dict[str, Var | str] | None = None,
  365. ) -> tuple[str, str]:
  366. """Compile the document root.
  367. Args:
  368. head_components: The components to include in the head.
  369. html_lang: The language of the document, will be added to the html root element.
  370. html_custom_attrs: custom attributes added to the html root element.
  371. Returns:
  372. The path and code of the compiled document root.
  373. """
  374. # Get the path for the output file.
  375. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  376. # Create the document root.
  377. document_root = utils.create_document_root(
  378. head_components, html_lang=html_lang, html_custom_attrs=html_custom_attrs
  379. )
  380. # Compile the document root.
  381. code = _compile_document_root(document_root)
  382. return output_path, code
  383. def compile_app(app_root: Component) -> tuple[str, str]:
  384. """Compile the app root.
  385. Args:
  386. app_root: The app root component to compile.
  387. Returns:
  388. The path and code of the compiled app wrapper.
  389. """
  390. # Get the path for the output file.
  391. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  392. # Compile the document root.
  393. code = _compile_app(app_root)
  394. return output_path, code
  395. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  396. """Compile the theme.
  397. Args:
  398. style: The style to compile.
  399. Returns:
  400. The path and code of the compiled theme.
  401. """
  402. output_path = utils.get_theme_path()
  403. # Create the theme.
  404. theme = utils.create_theme(style)
  405. # Compile the theme.
  406. code = _compile_theme(str(LiteralVar.create(theme)))
  407. return output_path, code
  408. def compile_contexts(
  409. state: type[BaseState] | None,
  410. theme: Component | None,
  411. ) -> tuple[str, str]:
  412. """Compile the initial state / context.
  413. Args:
  414. state: The app state.
  415. theme: The top-level app theme.
  416. Returns:
  417. The path and code of the compiled context.
  418. """
  419. # Get the path for the output file.
  420. output_path = utils.get_context_path()
  421. return output_path, _compile_contexts(state, theme)
  422. def compile_page(
  423. path: str, component: BaseComponent, state: type[BaseState] | None
  424. ) -> tuple[str, str]:
  425. """Compile a single page.
  426. Args:
  427. path: The path to compile the page to.
  428. component: The component to compile.
  429. state: The app state.
  430. Returns:
  431. The path and code of the compiled page.
  432. """
  433. # Get the path for the output file.
  434. output_path = utils.get_page_path(path)
  435. # Add the style to the component.
  436. code = _compile_page(component, state)
  437. return output_path, code
  438. def compile_components(
  439. components: set[CustomComponent],
  440. ) -> tuple[str, str, dict[str, list[ImportVar]]]:
  441. """Compile the custom components.
  442. Args:
  443. components: The custom components to compile.
  444. Returns:
  445. The path and code of the compiled components.
  446. """
  447. # Get the path for the output file.
  448. output_path = utils.get_components_path()
  449. # Compile the components.
  450. code, imports = _compile_components(components)
  451. return output_path, code, imports
  452. def compile_stateful_components(
  453. pages: Iterable[Component],
  454. ) -> tuple[str, str, list[BaseComponent]]:
  455. """Separately compile components that depend on State vars.
  456. StatefulComponents are compiled as their own component functions with their own
  457. useContext declarations, which allows page components to be stateless and avoid
  458. re-rendering along with parts of the page that actually depend on state.
  459. Args:
  460. pages: The pages to extract stateful components from.
  461. Returns:
  462. The path and code of the compiled stateful components.
  463. """
  464. output_path = utils.get_stateful_components_path()
  465. # Compile the stateful components.
  466. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  467. code = _compile_stateful_components(page_components)
  468. return output_path, code, page_components
  469. def compile_tailwind(
  470. config: dict,
  471. ):
  472. """Compile the Tailwind config.
  473. Args:
  474. config: The Tailwind config.
  475. Returns:
  476. The compiled Tailwind config.
  477. """
  478. # Get the path for the output file.
  479. output_path = str((get_web_dir() / constants.Tailwind.CONFIG).absolute())
  480. # Compile the config.
  481. code = _compile_tailwind(config)
  482. return output_path, code
  483. def remove_tailwind_from_postcss() -> tuple[str, str]:
  484. """If tailwind is not to be used, remove it from postcss.config.js.
  485. Returns:
  486. The path and code of the compiled postcss.config.js.
  487. """
  488. # Get the path for the output file.
  489. output_path = str(get_web_dir() / constants.Dirs.POSTCSS_JS)
  490. code = [
  491. line
  492. for line in Path(output_path).read_text().splitlines(keepends=True)
  493. if "tailwindcss: " not in line
  494. ]
  495. # Compile the config.
  496. return output_path, "".join(code)
  497. def purge_web_pages_dir():
  498. """Empty out .web/pages directory."""
  499. if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR.get():
  500. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
  501. return
  502. # Empty out the web pages directory.
  503. utils.empty_dir(get_web_dir() / constants.Dirs.PAGES, keep_files=["_app.js"])
  504. if TYPE_CHECKING:
  505. from reflex.app import ComponentCallable, UnevaluatedPage
  506. def _into_component_once(
  507. component: Component
  508. | ComponentCallable
  509. | tuple[Component, ...]
  510. | str
  511. | Var
  512. | int
  513. | float,
  514. ) -> Component | None:
  515. """Convert a component to a Component.
  516. Args:
  517. component: The component to convert.
  518. Returns:
  519. The converted component.
  520. """
  521. if isinstance(component, Component):
  522. return component
  523. if isinstance(component, (Var, int, float, str)):
  524. return Fragment.create(component)
  525. if isinstance(component, Sequence):
  526. return Fragment.create(*component)
  527. return None
  528. def readable_name_from_component(
  529. component: Component | ComponentCallable,
  530. ) -> str | None:
  531. """Get the readable name of a component.
  532. Args:
  533. component: The component to get the name of.
  534. Returns:
  535. The readable name of the component.
  536. """
  537. if isinstance(component, Component):
  538. return type(component).__name__
  539. if isinstance(component, (Var, int, float, str)):
  540. return str(component)
  541. if isinstance(component, Sequence):
  542. return ", ".join(str(c) for c in component)
  543. if callable(component):
  544. module_name = getattr(component, "__module__", None)
  545. if module_name is not None:
  546. module = getmodule(component)
  547. if module is not None:
  548. module_name = module.__name__
  549. if module_name is not None:
  550. return f"{module_name}.{component.__name__}"
  551. return component.__name__
  552. return None
  553. def into_component(component: Component | ComponentCallable) -> Component:
  554. """Convert a component to a Component.
  555. Args:
  556. component: The component to convert.
  557. Returns:
  558. The converted component.
  559. Raises:
  560. TypeError: If the component is not a Component.
  561. # noqa: DAR401
  562. """
  563. if (converted := _into_component_once(component)) is not None:
  564. return converted
  565. try:
  566. if (
  567. callable(component)
  568. and (converted := _into_component_once(component())) is not None
  569. ):
  570. return converted
  571. except KeyError as e:
  572. if isinstance(e, ReflexError):
  573. raise
  574. key = e.args[0] if e.args else None
  575. if key is not None and isinstance(key, Var):
  576. raise TypeError(
  577. "Cannot access a primitive map with a Var. Consider calling rx.Var.create() on the map."
  578. ).with_traceback(e.__traceback__) from None
  579. raise
  580. except TypeError as e:
  581. if isinstance(e, ReflexError):
  582. raise
  583. message = e.args[0] if e.args else None
  584. if message and isinstance(message, str):
  585. if message.endswith("has no len()") and (
  586. "ArrayCastedVar" in message
  587. or "ObjectCastedVar" in message
  588. or "StringCastedVar" in message
  589. ):
  590. raise TypeError(
  591. "Cannot pass a Var to a built-in function. Consider using .length() for accessing the length of an iterable Var."
  592. ).with_traceback(e.__traceback__) from None
  593. if message.endswith(
  594. "indices must be integers or slices, not NumberCastedVar"
  595. ) or message.endswith(
  596. "indices must be integers or slices, not BooleanCastedVar"
  597. ):
  598. raise TypeError(
  599. "Cannot index into a primitive sequence with a Var. Consider calling rx.Var.create() on the sequence."
  600. ).with_traceback(e.__traceback__) from None
  601. if "CastedVar" in str(e):
  602. raise TypeError(
  603. "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."
  604. ).with_traceback(e.__traceback__) from None
  605. raise
  606. raise TypeError(f"Expected a Component, got {type(component)}")
  607. def compile_unevaluated_page(
  608. route: str,
  609. page: UnevaluatedPage,
  610. state: type[BaseState] | None = None,
  611. style: ComponentStyle | None = None,
  612. theme: Component | None = None,
  613. ) -> tuple[Component, bool]:
  614. """Compiles an uncompiled page into a component and adds meta information.
  615. Args:
  616. route: The route of the page.
  617. page: The uncompiled page object.
  618. state: The state of the app.
  619. style: The style of the page.
  620. theme: The theme of the page.
  621. Returns:
  622. The compiled component and whether state should be enabled.
  623. """
  624. # Generate the component if it is a callable.
  625. component = into_component(page.component)
  626. component._add_style_recursive(style or {}, theme)
  627. enable_state = False
  628. # Ensure state is enabled if this page uses state.
  629. if state is None:
  630. if page.on_load or component._has_stateful_event_triggers():
  631. enable_state = True
  632. else:
  633. for var in component._get_vars(include_children=True):
  634. var_data = var._get_all_var_data()
  635. if not var_data:
  636. continue
  637. if not var_data.state:
  638. continue
  639. enable_state = True
  640. break
  641. from reflex.app import OverlayFragment
  642. from reflex.utils.format import make_default_page_title
  643. component = OverlayFragment.create(component)
  644. meta_args = {
  645. "title": (
  646. page.title
  647. if page.title is not None
  648. else make_default_page_title(get_config().app_name, route)
  649. ),
  650. "image": page.image,
  651. "meta": page.meta,
  652. }
  653. if page.description is not None:
  654. meta_args["description"] = page.description
  655. # Add meta information to the component.
  656. utils.add_meta(
  657. component,
  658. **meta_args,
  659. )
  660. return component, enable_state
  661. class ExecutorSafeFunctions:
  662. """Helper class to allow parallelisation of parts of the compilation process.
  663. This class (and its class attributes) are available at global scope.
  664. In a multiprocessing context (like when using a ProcessPoolExecutor), the content of this
  665. global class is logically replicated to any FORKED process.
  666. How it works:
  667. * Before the child process is forked, ensure that we stash any input data required by any future
  668. function call in the child process.
  669. * After the child process is forked, the child process will have a copy of the global class, which
  670. includes the previously stashed input data.
  671. * Any task submitted to the child process simply needs a way to communicate which input data the
  672. requested function call requires.
  673. Why do we need this? Passing input data directly to child process often not possible because the input data is not picklable.
  674. The mechanic described here removes the need to pickle the input data at all.
  675. Limitations:
  676. * This can never support returning unpicklable OUTPUT data.
  677. * Any object mutations done by the child process will not propagate back to the parent process (fork goes one way!).
  678. """
  679. COMPONENTS: dict[str, BaseComponent] = {}
  680. UNCOMPILED_PAGES: dict[str, UnevaluatedPage] = {}
  681. STATE: type[BaseState] | None = None
  682. @classmethod
  683. def compile_page(cls, route: str) -> tuple[str, str]:
  684. """Compile a page.
  685. Args:
  686. route: The route of the page to compile.
  687. Returns:
  688. The path and code of the compiled page.
  689. """
  690. return compile_page(route, cls.COMPONENTS[route], cls.STATE)
  691. @classmethod
  692. def compile_unevaluated_page(
  693. cls,
  694. route: str,
  695. style: ComponentStyle,
  696. theme: Component | None,
  697. ) -> tuple[str, Component, tuple[str, str]]:
  698. """Compile an unevaluated page.
  699. Args:
  700. route: The route of the page to compile.
  701. style: The style of the page.
  702. theme: The theme of the page.
  703. Returns:
  704. The route, compiled component, and compiled page.
  705. """
  706. component, enable_state = compile_unevaluated_page(
  707. route, cls.UNCOMPILED_PAGES[route], cls.STATE, style, theme
  708. )
  709. return route, component, compile_page(route, component, cls.STATE)
  710. @classmethod
  711. def compile_theme(cls, style: ComponentStyle | None) -> tuple[str, str]:
  712. """Compile the theme.
  713. Args:
  714. style: The style to compile.
  715. Returns:
  716. The path and code of the compiled theme.
  717. Raises:
  718. ValueError: If the style is not set.
  719. """
  720. if style is None:
  721. raise ValueError("STYLE should be set")
  722. return compile_theme(style)