utils.py 13 KB

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