banner.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """Banner components."""
  2. from __future__ import annotations
  3. from typing import Optional
  4. from reflex.components.base.bare import Bare
  5. from reflex.components.component import Component
  6. from reflex.components.core.cond import cond
  7. from reflex.components.el.elements.typography import Div
  8. from reflex.components.lucide.icon import Icon
  9. from reflex.components.radix.themes.components.dialog import (
  10. DialogContent,
  11. DialogRoot,
  12. DialogTitle,
  13. )
  14. from reflex.components.radix.themes.layout.flex import Flex
  15. from reflex.components.radix.themes.typography.text import Text
  16. from reflex.components.sonner.toast import Toaster, ToastProps
  17. from reflex.constants import Dirs, Hooks, Imports
  18. from reflex.constants.compiler import CompileVars
  19. from reflex.utils import imports
  20. from reflex.utils.serializers import serialize
  21. from reflex.vars import Var, VarData
  22. connect_error_var_data: VarData = VarData( # type: ignore
  23. imports=Imports.EVENTS,
  24. hooks={Hooks.EVENTS: None},
  25. )
  26. connect_errors: Var = Var.create_safe(
  27. value=CompileVars.CONNECT_ERROR,
  28. _var_is_local=True,
  29. _var_is_string=False,
  30. _var_data=connect_error_var_data,
  31. )
  32. connection_error: Var = Var.create_safe(
  33. value="(connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : ''",
  34. _var_is_local=False,
  35. _var_is_string=False,
  36. _var_data=connect_error_var_data,
  37. )
  38. connection_errors_count: Var = Var.create_safe(
  39. value="connectErrors.length",
  40. _var_is_string=False,
  41. _var_is_local=False,
  42. _var_data=connect_error_var_data,
  43. )
  44. has_connection_errors: Var = Var.create_safe(
  45. value="connectErrors.length > 0",
  46. _var_is_string=False,
  47. _var_data=connect_error_var_data,
  48. ).to(bool)
  49. has_too_many_connection_errors: Var = Var.create_safe(
  50. value="connectErrors.length >= 2",
  51. _var_is_string=False,
  52. _var_data=connect_error_var_data,
  53. ).to(bool)
  54. class WebsocketTargetURL(Bare):
  55. """A component that renders the websocket target URL."""
  56. def _get_imports(self) -> imports.ImportDict:
  57. return {
  58. f"/{Dirs.STATE_PATH}": [imports.ImportVar(tag="getBackendURL")],
  59. "/env.json": [imports.ImportVar(tag="env", is_default=True)],
  60. }
  61. @classmethod
  62. def create(cls) -> Component:
  63. """Create a websocket target URL component.
  64. Returns:
  65. The websocket target URL component.
  66. """
  67. return super().create(contents="{getBackendURL(env.EVENT).href}")
  68. def default_connection_error() -> list[str | Var | Component]:
  69. """Get the default connection error message.
  70. Returns:
  71. The default connection error message.
  72. """
  73. return [
  74. "Cannot connect to server: ",
  75. connection_error,
  76. ". Check if server is reachable at ",
  77. WebsocketTargetURL.create(),
  78. ]
  79. class ConnectionToaster(Toaster):
  80. """A connection toaster component."""
  81. def add_hooks(self) -> list[str]:
  82. """Add the hooks for the connection toaster.
  83. Returns:
  84. The hooks for the connection toaster.
  85. """
  86. toast_id = "websocket-error"
  87. target_url = WebsocketTargetURL.create()
  88. props = ToastProps( # type: ignore
  89. description=Var.create(
  90. f"`Check if server is reachable at ${target_url}`",
  91. _var_is_string=False,
  92. _var_is_local=False,
  93. ),
  94. close_button=True,
  95. duration=120000,
  96. id=toast_id,
  97. )
  98. hook = Var.create(
  99. f"""
  100. const toast_props = {serialize(props)};
  101. const [userDismissed, setUserDismissed] = useState(false);
  102. useEffect(() => {{
  103. if ({has_too_many_connection_errors}) {{
  104. if (!userDismissed) {{
  105. toast.error(
  106. `Cannot connect to server: {connection_error}.`,
  107. {{...toast_props, onDismiss: () => setUserDismissed(true)}},
  108. )
  109. }}
  110. }} else {{
  111. toast.dismiss("{toast_id}");
  112. setUserDismissed(false); // after reconnection reset dismissed state
  113. }}
  114. }}, [{connect_errors}]);""",
  115. _var_is_string=False,
  116. )
  117. hook._var_data = VarData.merge( # type: ignore
  118. connect_errors._var_data,
  119. VarData(
  120. imports={
  121. "react": [
  122. imports.ImportVar(tag="useEffect"),
  123. imports.ImportVar(tag="useState"),
  124. ],
  125. **target_url._get_imports(),
  126. }
  127. ),
  128. )
  129. return [
  130. Hooks.EVENTS,
  131. hook, # type: ignore
  132. ]
  133. class ConnectionBanner(Component):
  134. """A connection banner component."""
  135. @classmethod
  136. def create(cls, comp: Optional[Component] = None) -> Component:
  137. """Create a connection banner component.
  138. Args:
  139. comp: The component to render when there's a server connection error.
  140. Returns:
  141. The connection banner component.
  142. """
  143. if not comp:
  144. comp = Flex.create(
  145. Text.create(
  146. *default_connection_error(),
  147. color="black",
  148. size="4",
  149. ),
  150. justify="center",
  151. background_color="crimson",
  152. width="100vw",
  153. padding="5px",
  154. position="fixed",
  155. )
  156. return cond(has_connection_errors, comp)
  157. class ConnectionModal(Component):
  158. """A connection status modal window."""
  159. @classmethod
  160. def create(cls, comp: Optional[Component] = None) -> Component:
  161. """Create a connection banner component.
  162. Args:
  163. comp: The component to render when there's a server connection error.
  164. Returns:
  165. The connection banner component.
  166. """
  167. if not comp:
  168. comp = Text.create(*default_connection_error())
  169. return cond(
  170. has_too_many_connection_errors,
  171. DialogRoot.create(
  172. DialogContent.create(
  173. DialogTitle.create("Connection Error"),
  174. comp,
  175. ),
  176. open=has_too_many_connection_errors,
  177. z_index=9999,
  178. ),
  179. )
  180. class WifiOffPulse(Icon):
  181. """A wifi_off icon with an animated opacity pulse."""
  182. @classmethod
  183. def create(cls, **props) -> Component:
  184. """Create a wifi_off icon with an animated opacity pulse.
  185. Args:
  186. **props: The properties of the component.
  187. Returns:
  188. The icon component with default props applied.
  189. """
  190. return super().create(
  191. "wifi_off",
  192. color=props.pop("color", "crimson"),
  193. size=props.pop("size", 32),
  194. z_index=props.pop("z_index", 9999),
  195. position=props.pop("position", "fixed"),
  196. bottom=props.pop("botton", "33px"),
  197. right=props.pop("right", "33px"),
  198. animation=Var.create(f"${{pulse}} 1s infinite", _var_is_string=True),
  199. **props,
  200. )
  201. def _get_imports(self) -> imports.ImportDict:
  202. return imports.merge_imports(
  203. super()._get_imports(),
  204. {"@emotion/react": [imports.ImportVar(tag="keyframes")]},
  205. )
  206. def _get_custom_code(self) -> str | None:
  207. return """
  208. const pulse = keyframes`
  209. 0% {
  210. opacity: 0;
  211. }
  212. 100% {
  213. opacity: 1;
  214. }
  215. `
  216. """
  217. class ConnectionPulser(Div):
  218. """A connection pulser component."""
  219. @classmethod
  220. def create(cls, **props) -> Component:
  221. """Create a connection pulser component.
  222. Args:
  223. **props: The properties of the component.
  224. Returns:
  225. The connection pulser component.
  226. """
  227. return super().create(
  228. cond(
  229. has_connection_errors,
  230. WifiOffPulse.create(**props),
  231. ),
  232. title=f"Connection Error: {connection_error}",
  233. position="fixed",
  234. width="100vw",
  235. height="0",
  236. )
  237. connection_banner = ConnectionBanner.create
  238. connection_modal = ConnectionModal.create
  239. connection_toaster = ConnectionToaster.create
  240. connection_pulser = ConnectionPulser.create