dynamic.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """Components that are dynamically generated on the backend."""
  2. from typing import TYPE_CHECKING, Union
  3. from reflex import constants
  4. from reflex.utils import imports
  5. from reflex.utils.exceptions import DynamicComponentMissingLibraryError
  6. from reflex.utils.format import format_library_name
  7. from reflex.utils.serializers import serializer
  8. from reflex.vars import Var, get_unique_variable_name
  9. from reflex.vars.base import VarData, transform
  10. if TYPE_CHECKING:
  11. from reflex.components.component import Component
  12. def get_cdn_url(lib: str) -> str:
  13. """Get the CDN URL for a library.
  14. Args:
  15. lib: The library to get the CDN URL for.
  16. Returns:
  17. The CDN URL for the library.
  18. """
  19. return f"https://cdn.jsdelivr.net/npm/{lib}" + "/+esm"
  20. bundled_libraries = {
  21. "react",
  22. "@radix-ui/themes",
  23. "@emotion/react",
  24. "next/link",
  25. f"$/{constants.Dirs.UTILS}/context",
  26. f"$/{constants.Dirs.UTILS}/state",
  27. f"$/{constants.Dirs.UTILS}/components",
  28. }
  29. def bundle_library(component: Union["Component", str]):
  30. """Bundle a library with the component.
  31. Args:
  32. component: The component to bundle the library with.
  33. Raises:
  34. DynamicComponentMissingLibraryError: Raised when a dynamic component is missing a library.
  35. """
  36. if isinstance(component, str):
  37. bundled_libraries.add(component)
  38. return
  39. if component.library is None:
  40. msg = "Component must have a library to bundle."
  41. raise DynamicComponentMissingLibraryError(msg)
  42. bundled_libraries.add(format_library_name(component.library))
  43. def load_dynamic_serializer():
  44. """Load the serializer for dynamic components."""
  45. # Causes a circular import, so we import here.
  46. from reflex.components.component import Component
  47. @serializer
  48. def make_component(component: Component) -> str:
  49. """Generate the code for a dynamic component.
  50. Args:
  51. component: The component to generate code for.
  52. Returns:
  53. The generated code
  54. """
  55. # Causes a circular import, so we import here.
  56. from reflex.compiler import compiler, templates, utils
  57. from reflex.components.base.bare import Bare
  58. component = Bare.create(Var.create(component))
  59. rendered_components = {}
  60. # Include dynamic imports in the shared component.
  61. if dynamic_imports := component._get_all_dynamic_imports():
  62. rendered_components.update(dict.fromkeys(dynamic_imports))
  63. # Include custom code in the shared component.
  64. rendered_components.update(
  65. dict.fromkeys(component._get_all_custom_code()),
  66. )
  67. rendered_components[
  68. templates.STATEFUL_COMPONENT.render(
  69. tag_name="MySSRComponent",
  70. memo_trigger_hooks=[],
  71. component=component,
  72. )
  73. ] = None
  74. libs_in_window = bundled_libraries
  75. component_imports = component._get_all_imports()
  76. compiler._apply_common_imports(component_imports)
  77. imports = {}
  78. for lib, names in component_imports.items():
  79. formatted_lib_name = format_library_name(lib)
  80. if (
  81. not lib.startswith((".", "/", "$/"))
  82. and not lib.startswith("http")
  83. and formatted_lib_name not in libs_in_window
  84. ):
  85. imports[get_cdn_url(lib)] = names
  86. else:
  87. imports[lib] = names
  88. module_code_lines = templates.STATEFUL_COMPONENTS.render(
  89. imports=utils.compile_imports(imports),
  90. memoized_code="\n".join(rendered_components),
  91. ).splitlines()[1:]
  92. # Rewrite imports from `/` to destructure from window
  93. for ix, line in enumerate(module_code_lines[:]):
  94. if line.startswith("import "):
  95. if 'from "$/' in line or 'from "/' in line:
  96. module_code_lines[ix] = (
  97. line.replace("import ", "const ", 1)
  98. .replace(" as ", ": ")
  99. .replace(" from ", " = window['__reflex'][", 1)
  100. + "]"
  101. )
  102. else:
  103. for lib in libs_in_window:
  104. if f'from "{lib}"' in line:
  105. module_code_lines[ix] = (
  106. line.replace("import ", "const ", 1)
  107. .replace(
  108. f' from "{lib}"', f" = window.__reflex['{lib}']", 1
  109. )
  110. .replace(" as ", ": ")
  111. )
  112. if line.startswith("export function"):
  113. module_code_lines[ix] = line.replace(
  114. "export function", "export default function", 1
  115. )
  116. line_stripped = line.strip()
  117. if line_stripped.startswith("{") and line_stripped.endswith("}"):
  118. module_code_lines[ix] = line_stripped[1:-1]
  119. module_code_lines.insert(0, "const React = window.__reflex.react;")
  120. function_line = next(
  121. index
  122. for index, line in enumerate(module_code_lines)
  123. if line.startswith("export default function")
  124. )
  125. module_code_lines = [
  126. line
  127. for _, line in sorted(
  128. enumerate(module_code_lines),
  129. key=lambda x: (
  130. not (x[1].startswith("import ") and x[0] < function_line),
  131. x[0],
  132. ),
  133. )
  134. ]
  135. return "\n".join(
  136. [
  137. "//__reflex_evaluate",
  138. *module_code_lines,
  139. ]
  140. )
  141. @transform
  142. def evaluate_component(js_string: Var[str]) -> Var[Component]:
  143. """Evaluate a component.
  144. Args:
  145. js_string: The JavaScript string to evaluate.
  146. Returns:
  147. The evaluated JavaScript string.
  148. """
  149. unique_var_name = get_unique_variable_name()
  150. return js_string._replace(
  151. _js_expr=unique_var_name,
  152. _var_type=Component,
  153. merge_var_data=VarData.merge(
  154. VarData(
  155. imports={
  156. f"$/{constants.Dirs.STATE_PATH}": [
  157. imports.ImportVar(tag="evalReactComponent"),
  158. ],
  159. "react": [
  160. imports.ImportVar(tag="useState"),
  161. imports.ImportVar(tag="useEffect"),
  162. ],
  163. },
  164. hooks={
  165. f"const [{unique_var_name}, set_{unique_var_name}] = useState(null);": None,
  166. "useEffect(() => {"
  167. "let isMounted = true;"
  168. f"evalReactComponent({js_string!s})"
  169. ".then((component) => {"
  170. "if (isMounted) {"
  171. f"set_{unique_var_name}(component);"
  172. "}"
  173. "});"
  174. "return () => {"
  175. "isMounted = false;"
  176. "};"
  177. "}"
  178. f", [{js_string!s}]);": None,
  179. },
  180. ),
  181. ),
  182. )