utils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. """Common utility functions used in the compiler."""
  2. import os
  3. from typing import Dict, List, Optional, Set, Tuple, Type
  4. from reflex import constants
  5. from reflex.components.base import (
  6. Body,
  7. ColorModeScript,
  8. Description,
  9. DocumentHead,
  10. Head,
  11. Html,
  12. Image,
  13. Main,
  14. Meta,
  15. NextScript,
  16. RawLink,
  17. Title,
  18. )
  19. from reflex.components.component import Component, ComponentStyle, CustomComponent
  20. from reflex.state import State
  21. from reflex.style import Style
  22. from reflex.utils import format, imports, path_ops
  23. from reflex.vars import ImportVar
  24. # To re-export this function.
  25. merge_imports = imports.merge_imports
  26. def compile_import_statement(fields: Set[ImportVar]) -> Tuple[str, Set[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. # Check for default imports.
  36. defaults = {field for field in fields if field.is_default}
  37. assert len(defaults) < 2
  38. # Get the default import, and the specific imports.
  39. default = next(iter({field.name for field in defaults}), "")
  40. rest = {field.name for field in fields - defaults}
  41. return default, rest
  42. def validate_imports(imports: imports.ImportDict):
  43. """Verify that the same Tag is not used in multiple import.
  44. Args:
  45. imports: The dict of imports to validate
  46. Raises:
  47. ValueError: if a conflict on "tag/alias" is detected for an import.
  48. """
  49. used_tags = {}
  50. for lib, _imports in imports.items():
  51. for _import in _imports:
  52. import_name = (
  53. f"{_import.tag}/{_import.alias}" if _import.alias else _import.tag
  54. )
  55. if import_name in used_tags:
  56. raise ValueError(
  57. f"Can not compile, the tag {import_name} is used multiple time from {lib} and {used_tags[import_name]}"
  58. )
  59. used_tags[import_name] = lib
  60. def compile_imports(imports: imports.ImportDict) -> List[dict]:
  61. """Compile an import dict.
  62. Args:
  63. imports: The import dict to compile.
  64. Returns:
  65. The list of import dict.
  66. """
  67. import_dicts = []
  68. for lib, fields in imports.items():
  69. default, rest = compile_import_statement(fields)
  70. if not lib:
  71. assert not default, "No default field allowed for empty library."
  72. assert rest is not None and len(rest) > 0, "No fields to import."
  73. for module in sorted(rest):
  74. import_dicts.append(get_import_dict(module))
  75. continue
  76. import_dicts.append(get_import_dict(lib, default, rest))
  77. return import_dicts
  78. def get_import_dict(lib: str, default: str = "", rest: Optional[Set] = None) -> Dict:
  79. """Get dictionary for import template.
  80. Args:
  81. lib: The importing react library.
  82. default: The default module to import.
  83. rest: The rest module to import.
  84. Returns:
  85. A dictionary for import template.
  86. """
  87. return {
  88. "lib": lib,
  89. "default": default,
  90. "rest": rest if rest else set(),
  91. }
  92. def compile_state(state: Type[State]) -> Dict:
  93. """Compile the state of the app.
  94. Args:
  95. state: The app state object.
  96. Returns:
  97. A dictionary of the compiled state.
  98. """
  99. try:
  100. initial_state = state().dict()
  101. except Exception:
  102. initial_state = state().dict(include_computed=False)
  103. initial_state.update(
  104. {
  105. "files": [],
  106. }
  107. )
  108. return format.format_state(initial_state)
  109. def compile_custom_component(
  110. component: CustomComponent,
  111. ) -> Tuple[dict, imports.ImportDict]:
  112. """Compile a custom component.
  113. Args:
  114. component: The custom component to compile.
  115. Returns:
  116. A tuple of the compiled component and the imports required by the component.
  117. """
  118. # Render the component.
  119. render = component.get_component()
  120. # Get the imports.
  121. imports = {
  122. lib: fields
  123. for lib, fields in render.get_imports().items()
  124. if lib != component.library
  125. }
  126. # Concatenate the props.
  127. props = [prop.name for prop in component.get_prop_vars()]
  128. # Compile the component.
  129. return (
  130. {
  131. "name": component.tag,
  132. "props": props,
  133. "render": render.render(),
  134. },
  135. imports,
  136. )
  137. def create_document_root(stylesheets: List[str]) -> Component:
  138. """Create the document root.
  139. Args:
  140. stylesheets: The list of stylesheets to include in the document root.
  141. Returns:
  142. The document root.
  143. """
  144. sheets = [RawLink.create(rel="stylesheet", href=href) for href in stylesheets]
  145. return Html.create(
  146. DocumentHead.create(*sheets),
  147. Body.create(
  148. ColorModeScript.create(),
  149. Main.create(),
  150. NextScript.create(),
  151. ),
  152. )
  153. def create_theme(style: ComponentStyle) -> Dict:
  154. """Create the base style for the app.
  155. Args:
  156. style: The style dict for the app.
  157. Returns:
  158. The base style for the app.
  159. """
  160. # Get the global style from the style dict.
  161. global_style = Style({k: v for k, v in style.items() if not isinstance(k, type)})
  162. # Root styles.
  163. root_style = Style({k: v for k, v in global_style.items() if k.startswith("::")})
  164. # Body styles.
  165. root_style["body"] = Style(
  166. {k: v for k, v in global_style.items() if k not in root_style}
  167. )
  168. # Return the theme.
  169. return {
  170. "styles": {"global": root_style},
  171. }
  172. def get_page_path(path: str) -> str:
  173. """Get the path of the compiled JS file for the given page.
  174. Args:
  175. path: The path of the page.
  176. Returns:
  177. The path of the compiled JS file.
  178. """
  179. return os.path.join(constants.WEB_PAGES_DIR, path + constants.JS_EXT)
  180. def get_theme_path() -> str:
  181. """Get the path of the base theme style.
  182. Returns:
  183. The path of the theme style.
  184. """
  185. return os.path.join(constants.WEB_UTILS_DIR, constants.THEME + constants.JS_EXT)
  186. def get_context_path() -> str:
  187. """Get the path of the context / initial state file.
  188. Returns:
  189. The path of the context module.
  190. """
  191. return os.path.join(constants.WEB_UTILS_DIR, "context" + constants.JS_EXT)
  192. def get_components_path() -> str:
  193. """Get the path of the compiled components.
  194. Returns:
  195. The path of the compiled components.
  196. """
  197. return os.path.join(constants.WEB_UTILS_DIR, "components" + constants.JS_EXT)
  198. def get_asset_path(filename: Optional[str] = None) -> str:
  199. """Get the path for an asset.
  200. Args:
  201. filename: Optional, if given, is added to the root path of assets dir.
  202. Returns:
  203. The path of the asset.
  204. """
  205. if filename is None:
  206. return constants.WEB_ASSETS_DIR
  207. else:
  208. return os.path.join(constants.WEB_ASSETS_DIR, filename)
  209. def add_meta(
  210. page: Component, title: str, image: str, description: str, meta: List[Dict]
  211. ) -> Component:
  212. """Add metadata to a page.
  213. Args:
  214. page: The component for the page.
  215. title: The title of the page.
  216. image: The image for the page.
  217. description: The description of the page.
  218. meta: The metadata list.
  219. Returns:
  220. The component with the metadata added.
  221. """
  222. meta_tags = [Meta.create(**item) for item in meta]
  223. page.children.append(
  224. Head.create(
  225. Title.create(title),
  226. Description.create(content=description),
  227. Image.create(content=image),
  228. *meta_tags,
  229. )
  230. )
  231. return page
  232. def write_page(path: str, code: str):
  233. """Write the given code to the given path.
  234. Args:
  235. path: The path to write the code to.
  236. code: The code to write.
  237. """
  238. path_ops.mkdir(os.path.dirname(path))
  239. with open(path, "w", encoding="utf-8") as f:
  240. f.write(code)
  241. def empty_dir(path: str, keep_files: Optional[List[str]] = None):
  242. """Remove all files and folders in a directory except for the keep_files.
  243. Args:
  244. path: The path to the directory that will be emptied
  245. keep_files: List of filenames or foldernames that will not be deleted.
  246. """
  247. # If the directory does not exist, return.
  248. if not os.path.exists(path):
  249. return
  250. # Remove all files and folders in the directory.
  251. keep_files = keep_files or []
  252. directory_contents = os.listdir(path)
  253. for element in directory_contents:
  254. if element not in keep_files:
  255. path_ops.rm(os.path.join(path, element))