utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. """Common utility functions used in the compiler."""
  2. from __future__ import annotations
  3. import os
  4. from pathlib import Path
  5. from typing import Any, Callable, Dict, Optional, Type, Union
  6. from urllib.parse import urlparse
  7. from reflex.ivars.base import ImmutableVar
  8. from reflex.utils.prerequisites import get_web_dir
  9. try:
  10. from pydantic.v1.fields import ModelField
  11. except ModuleNotFoundError:
  12. from pydantic.fields import ModelField # type: ignore
  13. from reflex import constants
  14. from reflex.components.base import (
  15. Body,
  16. Description,
  17. DocumentHead,
  18. Head,
  19. Html,
  20. Image,
  21. Main,
  22. Meta,
  23. NextScript,
  24. Title,
  25. )
  26. from reflex.components.component import Component, ComponentStyle, CustomComponent
  27. from reflex.state import BaseState, Cookie, LocalStorage, SessionStorage
  28. from reflex.style import Style
  29. from reflex.utils import console, format, imports, path_ops
  30. from reflex.utils.imports import ImportVar, ParsedImportDict
  31. # To re-export this function.
  32. merge_imports = imports.merge_imports
  33. def compile_import_statement(fields: list[ImportVar]) -> tuple[str, list[str]]:
  34. """Compile an import statement.
  35. Args:
  36. fields: The set of fields to import from the library.
  37. Returns:
  38. The libraries for default and rest.
  39. default: default library. When install "import def from library".
  40. rest: rest of libraries. When install "import {rest1, rest2} from library"
  41. """
  42. # ignore the ImportVar fields with render=False during compilation
  43. fields_set = {field for field in fields if field.render}
  44. # Check for default imports.
  45. defaults = {field for field in fields_set if field.is_default}
  46. assert len(defaults) < 2
  47. # Get the default import, and the specific imports.
  48. default = next(iter({field.name for field in defaults}), "")
  49. rest = {field.name for field in fields_set - defaults}
  50. return default, list(rest)
  51. def validate_imports(import_dict: ParsedImportDict):
  52. """Verify that the same Tag is not used in multiple import.
  53. Args:
  54. import_dict: The dict of imports to validate
  55. Raises:
  56. ValueError: if a conflict on "tag/alias" is detected for an import.
  57. """
  58. used_tags = {}
  59. for lib, _imports in import_dict.items():
  60. for _import in _imports:
  61. import_name = (
  62. f"{_import.tag}/{_import.alias}" if _import.alias else _import.tag
  63. )
  64. if import_name in used_tags:
  65. raise ValueError(
  66. f"Can not compile, the tag {import_name} is used multiple time from {lib} and {used_tags[import_name]}"
  67. )
  68. if import_name is not None:
  69. used_tags[import_name] = lib
  70. def compile_imports(import_dict: ParsedImportDict) -> list[dict]:
  71. """Compile an import dict.
  72. Args:
  73. import_dict: The import dict to compile.
  74. Returns:
  75. The list of import dict.
  76. """
  77. collapsed_import_dict: ParsedImportDict = imports.collapse_imports(import_dict)
  78. validate_imports(collapsed_import_dict)
  79. import_dicts = []
  80. for lib, fields in collapsed_import_dict.items():
  81. default, rest = compile_import_statement(fields)
  82. # prevent lib from being rendered on the page if all imports are non rendered kind
  83. if not any({f.render for f in fields}): # type: ignore
  84. continue
  85. if not lib:
  86. assert not default, "No default field allowed for empty library."
  87. assert rest is not None and len(rest) > 0, "No fields to import."
  88. for module in sorted(rest):
  89. import_dicts.append(get_import_dict(module))
  90. continue
  91. # remove the version before rendering the package imports
  92. lib = format.format_library_name(lib)
  93. import_dicts.append(get_import_dict(lib, default, rest))
  94. return import_dicts
  95. def get_import_dict(lib: str, default: str = "", rest: list[str] | None = None) -> dict:
  96. """Get dictionary for import template.
  97. Args:
  98. lib: The importing react library.
  99. default: The default module to import.
  100. rest: The rest module to import.
  101. Returns:
  102. A dictionary for import template.
  103. """
  104. return {
  105. "lib": lib,
  106. "default": default,
  107. "rest": rest if rest else [],
  108. }
  109. def compile_state(state: Type[BaseState]) -> dict:
  110. """Compile the state of the app.
  111. Args:
  112. state: The app state object.
  113. Returns:
  114. A dictionary of the compiled state.
  115. """
  116. try:
  117. initial_state = state(_reflex_internal_init=True).dict(initial=True)
  118. except Exception as e:
  119. console.warn(
  120. f"Failed to compile initial state with computed vars, excluding them: {e}"
  121. )
  122. initial_state = state(_reflex_internal_init=True).dict(
  123. initial=True, include_computed=False
  124. )
  125. return format.format_state(initial_state)
  126. def _compile_client_storage_field(
  127. field: ModelField,
  128. ) -> tuple[
  129. Type[Cookie] | Type[LocalStorage] | Type[SessionStorage] | None,
  130. dict[str, Any] | None,
  131. ]:
  132. """Compile the given cookie, local_storage or session_storage field.
  133. Args:
  134. field: The possible cookie field to compile.
  135. Returns:
  136. A dictionary of the compiled cookie or None if the field is not cookie-like.
  137. """
  138. for field_type in (Cookie, LocalStorage, SessionStorage):
  139. if isinstance(field.default, field_type):
  140. cs_obj = field.default
  141. elif isinstance(field.type_, type) and issubclass(field.type_, field_type):
  142. cs_obj = field.type_()
  143. else:
  144. continue
  145. return field_type, cs_obj.options()
  146. return None, None
  147. def _compile_client_storage_recursive(
  148. state: Type[BaseState],
  149. ) -> tuple[dict[str, dict], dict[str, dict], dict[str, dict]]:
  150. """Compile the client-side storage for the given state recursively.
  151. Args:
  152. state: The app state object.
  153. Returns:
  154. A tuple of the compiled client-side storage info:
  155. (
  156. cookies: dict[str, dict],
  157. local_storage: dict[str, dict[str, str]]
  158. session_storage: dict[str, dict[str, str]]
  159. ).
  160. """
  161. cookies = {}
  162. local_storage = {}
  163. session_storage = {}
  164. state_name = state.get_full_name()
  165. for name, field in state.__fields__.items():
  166. if name in state.inherited_vars:
  167. # only include vars defined in this state
  168. continue
  169. state_key = f"{state_name}.{name}"
  170. field_type, options = _compile_client_storage_field(field)
  171. if field_type is Cookie:
  172. cookies[state_key] = options
  173. elif field_type is LocalStorage:
  174. local_storage[state_key] = options
  175. elif field_type is SessionStorage:
  176. session_storage[state_key] = options
  177. else:
  178. continue
  179. for substate in state.get_substates():
  180. (
  181. substate_cookies,
  182. substate_local_storage,
  183. substate_session_storage,
  184. ) = _compile_client_storage_recursive(substate)
  185. cookies.update(substate_cookies)
  186. local_storage.update(substate_local_storage)
  187. session_storage.update(substate_session_storage)
  188. return cookies, local_storage, session_storage
  189. def compile_client_storage(state: Type[BaseState]) -> dict[str, dict]:
  190. """Compile the client-side storage for the given state.
  191. Args:
  192. state: The app state object.
  193. Returns:
  194. A dictionary of the compiled client-side storage info.
  195. """
  196. cookies, local_storage, session_storage = _compile_client_storage_recursive(state)
  197. return {
  198. constants.COOKIES: cookies,
  199. constants.LOCAL_STORAGE: local_storage,
  200. constants.SESSION_STORAGE: session_storage,
  201. }
  202. def compile_custom_component(
  203. component: CustomComponent,
  204. ) -> tuple[dict, ParsedImportDict]:
  205. """Compile a custom component.
  206. Args:
  207. component: The custom component to compile.
  208. Returns:
  209. A tuple of the compiled component and the imports required by the component.
  210. """
  211. # Render the component.
  212. render = component.get_component(component)
  213. # Get the imports.
  214. imports: ParsedImportDict = {
  215. lib: fields
  216. for lib, fields in render._get_all_imports().items()
  217. if lib != component.library
  218. }
  219. # Concatenate the props.
  220. props = [prop._var_name for prop in component.get_prop_vars()]
  221. # Compile the component.
  222. return (
  223. {
  224. "name": component.tag,
  225. "props": props,
  226. "render": render.render(),
  227. "hooks": {**render._get_all_hooks_internal(), **render._get_all_hooks()},
  228. "custom_code": render._get_all_custom_code(),
  229. },
  230. imports,
  231. )
  232. def create_document_root(
  233. head_components: list[Component] | None = None,
  234. html_lang: Optional[str] = None,
  235. html_custom_attrs: Optional[Dict[str, Union[ImmutableVar, str]]] = None,
  236. ) -> Component:
  237. """Create the document root.
  238. Args:
  239. head_components: The components to add to the head.
  240. html_lang: The language of the document, will be added to the html root element.
  241. html_custom_attrs: custom attributes added to the html root element.
  242. Returns:
  243. The document root.
  244. """
  245. head_components = head_components or []
  246. return Html.create(
  247. DocumentHead.create(*head_components),
  248. Body.create(
  249. Main.create(),
  250. NextScript.create(),
  251. ),
  252. lang=html_lang or "en",
  253. custom_attrs=html_custom_attrs or {},
  254. )
  255. def create_theme(style: ComponentStyle) -> dict:
  256. """Create the base style for the app.
  257. Args:
  258. style: The style dict for the app.
  259. Returns:
  260. The base style for the app.
  261. """
  262. # Get the global style from the style dict.
  263. style_rules = Style({k: v for k, v in style.items() if not isinstance(k, Callable)})
  264. root_style = {
  265. # Root styles.
  266. ":root": Style(
  267. {f"*{k}": v for k, v in style_rules.items() if k.startswith(":")}
  268. ),
  269. # Body styles.
  270. "body": Style(
  271. {k: v for k, v in style_rules.items() if not k.startswith(":")},
  272. ),
  273. }
  274. # Return the theme.
  275. return {"styles": {"global": root_style}}
  276. def get_page_path(path: str) -> str:
  277. """Get the path of the compiled JS file for the given page.
  278. Args:
  279. path: The path of the page.
  280. Returns:
  281. The path of the compiled JS file.
  282. """
  283. return str(get_web_dir() / constants.Dirs.PAGES / (path + constants.Ext.JS))
  284. def get_theme_path() -> str:
  285. """Get the path of the base theme style.
  286. Returns:
  287. The path of the theme style.
  288. """
  289. return str(
  290. get_web_dir()
  291. / constants.Dirs.UTILS
  292. / (constants.PageNames.THEME + constants.Ext.JS)
  293. )
  294. def get_root_stylesheet_path() -> str:
  295. """Get the path of the app root file.
  296. Returns:
  297. The path of the app root file.
  298. """
  299. return str(
  300. get_web_dir()
  301. / constants.Dirs.STYLES
  302. / (constants.PageNames.STYLESHEET_ROOT + constants.Ext.CSS)
  303. )
  304. def get_context_path() -> str:
  305. """Get the path of the context / initial state file.
  306. Returns:
  307. The path of the context module.
  308. """
  309. return str(get_web_dir() / (constants.Dirs.CONTEXTS_PATH + constants.Ext.JS))
  310. def get_components_path() -> str:
  311. """Get the path of the compiled components.
  312. Returns:
  313. The path of the compiled components.
  314. """
  315. return str(
  316. get_web_dir()
  317. / constants.Dirs.UTILS
  318. / (constants.PageNames.COMPONENTS + constants.Ext.JS),
  319. )
  320. def get_stateful_components_path() -> str:
  321. """Get the path of the compiled stateful components.
  322. Returns:
  323. The path of the compiled stateful components.
  324. """
  325. return str(
  326. get_web_dir()
  327. / constants.Dirs.UTILS
  328. / (constants.PageNames.STATEFUL_COMPONENTS + constants.Ext.JS)
  329. )
  330. def add_meta(
  331. page: Component,
  332. title: str,
  333. image: str,
  334. meta: list[dict],
  335. description: str | None = None,
  336. ) -> Component:
  337. """Add metadata to a page.
  338. Args:
  339. page: The component for the page.
  340. title: The title of the page.
  341. image: The image for the page.
  342. meta: The metadata list.
  343. description: The description of the page.
  344. Returns:
  345. The component with the metadata added.
  346. """
  347. meta_tags = [Meta.create(**item) for item in meta]
  348. children: list[Any] = [
  349. Title.create(title),
  350. ]
  351. if description:
  352. children.append(Description.create(content=description))
  353. children.append(Image.create(content=image))
  354. page.children.append(
  355. Head.create(
  356. *children,
  357. *meta_tags,
  358. )
  359. )
  360. return page
  361. def write_page(path: str, code: str):
  362. """Write the given code to the given path.
  363. Args:
  364. path: The path to write the code to.
  365. code: The code to write.
  366. """
  367. path_ops.mkdir(os.path.dirname(path))
  368. with open(path, "w", encoding="utf-8") as f:
  369. f.write(code)
  370. def empty_dir(path: str | Path, keep_files: list[str] | None = None):
  371. """Remove all files and folders in a directory except for the keep_files.
  372. Args:
  373. path: The path to the directory that will be emptied
  374. keep_files: List of filenames or foldernames that will not be deleted.
  375. """
  376. path = Path(path)
  377. # If the directory does not exist, return.
  378. if not path.exists():
  379. return
  380. # Remove all files and folders in the directory.
  381. keep_files = keep_files or []
  382. for element in path.iterdir():
  383. if element.name not in keep_files:
  384. path_ops.rm(element)
  385. def is_valid_url(url) -> bool:
  386. """Check if a url is valid.
  387. Args:
  388. url: The Url to check.
  389. Returns:
  390. Whether url is valid.
  391. """
  392. result = urlparse(url)
  393. return all([result.scheme, result.netloc])