utils.py 13 KB

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