banner.py 8.8 KB

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