banner.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. """Banner components."""
  2. from __future__ import annotations
  3. from typing import Optional
  4. from reflex.components.base.fragment import Fragment
  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 ImportVar
  20. from reflex.vars import VarData
  21. from reflex.vars.base import LiteralVar, Var
  22. from reflex.vars.function import FunctionStringVar
  23. from reflex.vars.number import BooleanVar
  24. from reflex.vars.sequence import LiteralArrayVar
  25. connect_error_var_data: VarData = VarData( # type: ignore
  26. imports=Imports.EVENTS,
  27. hooks={Hooks.EVENTS: None},
  28. )
  29. connect_errors = Var(
  30. _js_expr=CompileVars.CONNECT_ERROR, _var_data=connect_error_var_data
  31. )
  32. connection_error = Var(
  33. _js_expr="((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')",
  34. _var_data=connect_error_var_data,
  35. )
  36. connection_errors_count = Var(
  37. _js_expr="connectErrors.length", _var_data=connect_error_var_data
  38. )
  39. has_connection_errors = Var(
  40. _js_expr="(connectErrors.length > 0)", _var_data=connect_error_var_data
  41. ).to(BooleanVar)
  42. has_too_many_connection_errors = Var(
  43. _js_expr="(connectErrors.length >= 2)", _var_data=connect_error_var_data
  44. ).to(BooleanVar)
  45. class WebsocketTargetURL(Var):
  46. """A component that renders the websocket target URL."""
  47. @classmethod
  48. def create(cls) -> Var:
  49. """Create a websocket target URL component.
  50. Returns:
  51. The websocket target URL component.
  52. """
  53. return Var(
  54. _js_expr="getBackendURL(env.EVENT).href",
  55. _var_data=VarData(
  56. imports={
  57. "$/env.json": [ImportVar(tag="env", is_default=True)],
  58. f"$/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
  59. },
  60. ),
  61. _var_type=WebsocketTargetURL,
  62. )
  63. def default_connection_error() -> list[str | Var | Component]:
  64. """Get the default connection error message.
  65. Returns:
  66. The default connection error message.
  67. """
  68. return [
  69. "Cannot connect to server: ",
  70. connection_error,
  71. ". Check if server is reachable at ",
  72. WebsocketTargetURL.create(),
  73. ]
  74. class ConnectionToaster(Toaster):
  75. """A connection toaster component."""
  76. def add_hooks(self) -> list[str | Var]:
  77. """Add the hooks for the connection toaster.
  78. Returns:
  79. The hooks for the connection toaster.
  80. """
  81. toast_id = "websocket-error"
  82. target_url = WebsocketTargetURL.create()
  83. props = ToastProps( # type: ignore
  84. description=LiteralVar.create(
  85. f"Check if server is reachable at {target_url}",
  86. ),
  87. close_button=True,
  88. duration=120000,
  89. id=toast_id,
  90. )
  91. individual_hooks = [
  92. f"const toast_props = {LiteralVar.create(props)!s};",
  93. "const [userDismissed, setUserDismissed] = useState(false);",
  94. FunctionStringVar(
  95. "useEffect",
  96. _var_data=VarData(
  97. imports={
  98. "react": ["useEffect", "useState"],
  99. **dict(target_url._get_all_var_data().imports), # type: ignore
  100. }
  101. ),
  102. ).call(
  103. # TODO: This breaks the assumption that Vars are JS expressions
  104. Var(
  105. _js_expr=f"""
  106. () => {{
  107. if ({has_too_many_connection_errors!s}) {{
  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. }}
  119. """
  120. ),
  121. LiteralArrayVar.create([connect_errors]),
  122. ),
  123. ]
  124. return [
  125. Hooks.EVENTS,
  126. *individual_hooks,
  127. ]
  128. @classmethod
  129. def create(cls, *children, **props) -> Component:
  130. """Create a connection toaster component.
  131. Args:
  132. *children: The children of the component.
  133. **props: The properties of the component.
  134. Returns:
  135. The connection toaster component.
  136. """
  137. Toaster.is_used = True
  138. return super().create(*children, **props)
  139. class ConnectionBanner(Fragment):
  140. """A connection banner component."""
  141. @classmethod
  142. def create(cls, comp: Optional[Component] = None) -> Component:
  143. """Create a connection banner component.
  144. Args:
  145. comp: The component to render when there's a server connection error.
  146. Returns:
  147. The connection banner component.
  148. """
  149. if not comp:
  150. comp = Flex.create(
  151. Text.create(
  152. *default_connection_error(),
  153. color="black",
  154. size="4",
  155. ),
  156. justify="center",
  157. background_color="crimson",
  158. width="100vw",
  159. padding="5px",
  160. position="fixed",
  161. )
  162. return super().create(cond(has_connection_errors, comp))
  163. class ConnectionModal(Fragment):
  164. """A connection status modal window."""
  165. @classmethod
  166. def create(cls, comp: Optional[Component] = None) -> Component:
  167. """Create a connection banner component.
  168. Args:
  169. comp: The component to render when there's a server connection error.
  170. Returns:
  171. The connection banner component.
  172. """
  173. if not comp:
  174. comp = Text.create(*default_connection_error())
  175. return super().create(
  176. cond(
  177. has_too_many_connection_errors,
  178. DialogRoot.create(
  179. DialogContent.create(
  180. DialogTitle.create("Connection Error"),
  181. comp,
  182. ),
  183. open=has_too_many_connection_errors,
  184. z_index=9999,
  185. ),
  186. )
  187. )
  188. class WifiOffPulse(Icon):
  189. """A wifi_off icon with an animated opacity pulse."""
  190. @classmethod
  191. def create(cls, *children, **props) -> Icon:
  192. """Create a wifi_off icon with an animated opacity pulse.
  193. Args:
  194. *children: The children of the component.
  195. **props: The properties of the component.
  196. Returns:
  197. The icon component with default props applied.
  198. """
  199. pulse_var = Var(_js_expr="pulse")
  200. return super().create(
  201. "wifi_off",
  202. color=props.pop("color", "crimson"),
  203. size=props.pop("size", 32),
  204. z_index=props.pop("z_index", 9999),
  205. position=props.pop("position", "fixed"),
  206. bottom=props.pop("bottom", "33px"),
  207. right=props.pop("right", "33px"),
  208. animation=LiteralVar.create(f"{pulse_var} 1s infinite"),
  209. **props,
  210. )
  211. def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]:
  212. """Add imports for the WifiOffPulse component.
  213. Returns:
  214. The import dict.
  215. """
  216. return {"@emotion/react": [ImportVar(tag="keyframes")]}
  217. def _get_custom_code(self) -> str | None:
  218. return """
  219. const pulse = keyframes`
  220. 0% {
  221. opacity: 0;
  222. }
  223. 100% {
  224. opacity: 1;
  225. }
  226. `
  227. """
  228. class ConnectionPulser(Div):
  229. """A connection pulser component."""
  230. @classmethod
  231. def create(cls, **props) -> Component:
  232. """Create a connection pulser component.
  233. Args:
  234. **props: The properties of the component.
  235. Returns:
  236. The connection pulser component.
  237. """
  238. return super().create(
  239. cond(
  240. has_connection_errors,
  241. WifiOffPulse.create(**props),
  242. ),
  243. title=f"Connection Error: {connection_error}",
  244. position="fixed",
  245. width="100vw",
  246. height="0",
  247. )
  248. connection_banner = ConnectionBanner.create
  249. connection_modal = ConnectionModal.create
  250. connection_toaster = ConnectionToaster.create
  251. connection_pulser = ConnectionPulser.create