1
0

utils.py 13 KB

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