dynamic.py 6.3 KB

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