compiler.py 25 KB

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