banner.py 8.5 KB

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