1
0

utils.py 15 KB

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