utils.py 7.6 KB

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