dynamic.py 7.1 KB

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