utils.py 13 KB

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