1
0

dynamic.py 7.1 KB

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