banner.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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.imports import ImportDict, ImportVar
  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 add_imports(self) -> ImportDict:
  57. """Add imports for the websocket target URL component.
  58. Returns:
  59. The import dict.
  60. """
  61. return {
  62. f"/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
  63. "/env.json": [ImportVar(tag="env", is_default=True)],
  64. }
  65. @classmethod
  66. def create(cls) -> Component:
  67. """Create a websocket target URL component.
  68. Returns:
  69. The websocket target URL component.
  70. """
  71. return super().create(contents="{getBackendURL(env.EVENT).href}")
  72. def default_connection_error() -> list[str | Var | Component]:
  73. """Get the default connection error message.
  74. Returns:
  75. The default connection error message.
  76. """
  77. return [
  78. "Cannot connect to server: ",
  79. connection_error,
  80. ". Check if server is reachable at ",
  81. WebsocketTargetURL.create(),
  82. ]
  83. class ConnectionToaster(Toaster):
  84. """A connection toaster component."""
  85. def add_hooks(self) -> list[str | Var]:
  86. """Add the hooks for the connection toaster.
  87. Returns:
  88. The hooks for the connection toaster.
  89. """
  90. toast_id = "websocket-error"
  91. target_url = WebsocketTargetURL.create()
  92. props = ToastProps( # type: ignore
  93. description=Var.create(
  94. f"`Check if server is reachable at ${target_url}`",
  95. _var_is_string=False,
  96. _var_is_local=False,
  97. ),
  98. close_button=True,
  99. duration=120000,
  100. id=toast_id,
  101. )
  102. hook = Var.create_safe(
  103. f"""
  104. const toast_props = {serialize(props)};
  105. const [userDismissed, setUserDismissed] = useState(false);
  106. useEffect(() => {{
  107. if ({has_too_many_connection_errors}) {{
  108. if (!userDismissed) {{
  109. toast.error(
  110. `Cannot connect to server: {connection_error}.`,
  111. {{...toast_props, onDismiss: () => setUserDismissed(true)}},
  112. )
  113. }}
  114. }} else {{
  115. toast.dismiss("{toast_id}");
  116. setUserDismissed(false); // after reconnection reset dismissed state
  117. }}
  118. }}, [{connect_errors}]);""",
  119. _var_is_string=False,
  120. )
  121. imports: ImportDict = {
  122. "react": ["useEffect", "useState"],
  123. **target_url._get_imports(), # type: ignore
  124. }
  125. hook._var_data = VarData.merge(
  126. connect_errors._var_data,
  127. VarData(imports=imports),
  128. )
  129. return [
  130. Hooks.EVENTS,
  131. hook,
  132. ]
  133. @classmethod
  134. def create(cls, *children, **props) -> Component:
  135. """Create a connection toaster component.
  136. Args:
  137. *children: The children of the component.
  138. **props: The properties of the component.
  139. Returns:
  140. The connection toaster component.
  141. """
  142. Toaster.is_used = True
  143. return super().create(*children, **props)
  144. class ConnectionBanner(Component):
  145. """A connection banner component."""
  146. @classmethod
  147. def create(cls, comp: Optional[Component] = None) -> Component:
  148. """Create a connection banner component.
  149. Args:
  150. comp: The component to render when there's a server connection error.
  151. Returns:
  152. The connection banner component.
  153. """
  154. if not comp:
  155. comp = Flex.create(
  156. Text.create(
  157. *default_connection_error(),
  158. color="black",
  159. size="4",
  160. ),
  161. justify="center",
  162. background_color="crimson",
  163. width="100vw",
  164. padding="5px",
  165. position="fixed",
  166. )
  167. return cond(has_connection_errors, comp)
  168. class ConnectionModal(Component):
  169. """A connection status modal window."""
  170. @classmethod
  171. def create(cls, comp: Optional[Component] = None) -> Component:
  172. """Create a connection banner component.
  173. Args:
  174. comp: The component to render when there's a server connection error.
  175. Returns:
  176. The connection banner component.
  177. """
  178. if not comp:
  179. comp = Text.create(*default_connection_error())
  180. return cond(
  181. has_too_many_connection_errors,
  182. DialogRoot.create(
  183. DialogContent.create(
  184. DialogTitle.create("Connection Error"),
  185. comp,
  186. ),
  187. open=has_too_many_connection_errors,
  188. z_index=9999,
  189. ),
  190. )
  191. class WifiOffPulse(Icon):
  192. """A wifi_off icon with an animated opacity pulse."""
  193. @classmethod
  194. def create(cls, *children, **props) -> Icon:
  195. """Create a wifi_off icon with an animated opacity pulse.
  196. Args:
  197. *children: The children of the component.
  198. **props: The properties of the component.
  199. Returns:
  200. The icon component with default props applied.
  201. """
  202. return super().create(
  203. "wifi_off",
  204. color=props.pop("color", "crimson"),
  205. size=props.pop("size", 32),
  206. z_index=props.pop("z_index", 9999),
  207. position=props.pop("position", "fixed"),
  208. bottom=props.pop("botton", "33px"),
  209. right=props.pop("right", "33px"),
  210. animation=Var.create(f"${{pulse}} 1s infinite", _var_is_string=True),
  211. **props,
  212. )
  213. def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]:
  214. """Add imports for the WifiOffPulse component.
  215. Returns:
  216. The import dict.
  217. """
  218. return {"@emotion/react": [ImportVar(tag="keyframes")]}
  219. def _get_custom_code(self) -> str | None:
  220. return """
  221. const pulse = keyframes`
  222. 0% {
  223. opacity: 0;
  224. }
  225. 100% {
  226. opacity: 1;
  227. }
  228. `
  229. """
  230. class ConnectionPulser(Div):
  231. """A connection pulser component."""
  232. @classmethod
  233. def create(cls, **props) -> Component:
  234. """Create a connection pulser component.
  235. Args:
  236. **props: The properties of the component.
  237. Returns:
  238. The connection pulser component.
  239. """
  240. return super().create(
  241. cond(
  242. has_connection_errors,
  243. WifiOffPulse.create(**props),
  244. ),
  245. title=f"Connection Error: {connection_error}",
  246. position="fixed",
  247. width="100vw",
  248. height="0",
  249. )
  250. connection_banner = ConnectionBanner.create
  251. connection_modal = ConnectionModal.create
  252. connection_toaster = ConnectionToaster.create
  253. connection_pulser = ConnectionPulser.create