banner.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 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. )
  116. hook._var_data = VarData.merge( # type: ignore
  117. connect_errors._var_data,
  118. VarData(
  119. imports={
  120. "react": [
  121. imports.ImportVar(tag="useEffect"),
  122. imports.ImportVar(tag="useState"),
  123. ],
  124. **target_url._get_imports(),
  125. }
  126. ),
  127. )
  128. return [
  129. Hooks.EVENTS,
  130. hook, # type: ignore
  131. ]
  132. class ConnectionBanner(Component):
  133. """A connection banner component."""
  134. @classmethod
  135. def create(cls, comp: Optional[Component] = None) -> Component:
  136. """Create a connection banner component.
  137. Args:
  138. comp: The component to render when there's a server connection error.
  139. Returns:
  140. The connection banner component.
  141. """
  142. if not comp:
  143. comp = Flex.create(
  144. Text.create(
  145. *default_connection_error(),
  146. color="black",
  147. size="4",
  148. ),
  149. justify="center",
  150. background_color="crimson",
  151. width="100vw",
  152. padding="5px",
  153. position="fixed",
  154. )
  155. return cond(has_connection_errors, comp)
  156. class ConnectionModal(Component):
  157. """A connection status modal window."""
  158. @classmethod
  159. def create(cls, comp: Optional[Component] = None) -> Component:
  160. """Create a connection banner component.
  161. Args:
  162. comp: The component to render when there's a server connection error.
  163. Returns:
  164. The connection banner component.
  165. """
  166. if not comp:
  167. comp = Text.create(*default_connection_error())
  168. return cond(
  169. has_too_many_connection_errors,
  170. DialogRoot.create(
  171. DialogContent.create(
  172. DialogTitle.create("Connection Error"),
  173. comp,
  174. ),
  175. open=has_too_many_connection_errors,
  176. z_index=9999,
  177. ),
  178. )
  179. class WifiOffPulse(Icon):
  180. """A wifi_off icon with an animated opacity pulse."""
  181. @classmethod
  182. def create(cls, **props) -> Component:
  183. """Create a wifi_off icon with an animated opacity pulse.
  184. Args:
  185. **props: The properties of the component.
  186. Returns:
  187. The icon component with default props applied.
  188. """
  189. return super().create(
  190. "wifi_off",
  191. color=props.pop("color", "crimson"),
  192. size=props.pop("size", 32),
  193. z_index=props.pop("z_index", 9999),
  194. position=props.pop("position", "fixed"),
  195. bottom=props.pop("botton", "33px"),
  196. right=props.pop("right", "33px"),
  197. animation=Var.create(f"${{pulse}} 1s infinite", _var_is_string=True),
  198. **props,
  199. )
  200. def _get_imports(self) -> imports.ImportDict:
  201. return imports.merge_imports(
  202. super()._get_imports(),
  203. {"@emotion/react": [imports.ImportVar(tag="keyframes")]},
  204. )
  205. def _get_custom_code(self) -> str | None:
  206. return """
  207. const pulse = keyframes`
  208. 0% {
  209. opacity: 0;
  210. }
  211. 100% {
  212. opacity: 1;
  213. }
  214. `
  215. """
  216. class ConnectionPulser(Div):
  217. """A connection pulser component."""
  218. @classmethod
  219. def create(cls, **props) -> Component:
  220. """Create a connection pulser component.
  221. Args:
  222. **props: The properties of the component.
  223. Returns:
  224. The connection pulser component.
  225. """
  226. return super().create(
  227. cond(
  228. has_connection_errors,
  229. WifiOffPulse.create(**props),
  230. ),
  231. title=f"Connection Error: {connection_error}",
  232. position="fixed",
  233. width="100vw",
  234. height="0",
  235. )