utils.py 14 KB

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