banner.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. """Banner components."""
  2. from __future__ import annotations
  3. from typing import Optional
  4. from reflex import constants
  5. from reflex.components.component import Component
  6. from reflex.components.core.cond import cond
  7. from reflex.components.datadisplay.logo import svg_logo
  8. from reflex.components.el.elements.typography import Div
  9. from reflex.components.lucide.icon import Icon
  10. from reflex.components.radix.themes.components.dialog import (
  11. DialogContent,
  12. DialogRoot,
  13. DialogTitle,
  14. )
  15. from reflex.components.radix.themes.layout.flex import Flex
  16. from reflex.components.radix.themes.typography.text import Text
  17. from reflex.components.sonner.toast import Toaster, ToastProps
  18. from reflex.constants import Dirs, Hooks, Imports
  19. from reflex.constants.compiler import CompileVars
  20. from reflex.utils.imports import ImportVar
  21. from reflex.vars import VarData
  22. from reflex.vars.base import LiteralVar, Var
  23. from reflex.vars.function import FunctionStringVar
  24. from reflex.vars.number import BooleanVar
  25. from reflex.vars.sequence import LiteralArrayVar
  26. connect_error_var_data: VarData = VarData(
  27. imports=Imports.EVENTS,
  28. hooks={Hooks.EVENTS: None},
  29. )
  30. connect_errors = Var(
  31. _js_expr=CompileVars.CONNECT_ERROR, _var_data=connect_error_var_data
  32. )
  33. connection_error = Var(
  34. _js_expr="((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')",
  35. _var_data=connect_error_var_data,
  36. )
  37. connection_errors_count = Var(
  38. _js_expr="connectErrors.length", _var_data=connect_error_var_data
  39. )
  40. has_connection_errors = Var(
  41. _js_expr="(connectErrors.length > 0)", _var_data=connect_error_var_data
  42. ).to(BooleanVar)
  43. has_too_many_connection_errors = Var(
  44. _js_expr="(connectErrors.length >= 2)", _var_data=connect_error_var_data
  45. ).to(BooleanVar)
  46. class WebsocketTargetURL(Var):
  47. """A component that renders the websocket target URL."""
  48. @classmethod
  49. def create(cls) -> Var:
  50. """Create a websocket target URL component.
  51. Returns:
  52. The websocket target URL component.
  53. """
  54. return Var(
  55. _js_expr="getBackendURL(env.EVENT).href",
  56. _var_data=VarData(
  57. imports={
  58. "$/env.json": [ImportVar(tag="env", is_default=True)],
  59. f"$/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
  60. },
  61. ),
  62. _var_type=WebsocketTargetURL,
  63. )
  64. def default_connection_error() -> list[str | Var | Component]:
  65. """Get the default connection error message.
  66. Returns:
  67. The default connection error message.
  68. """
  69. return [
  70. "Cannot connect to server: ",
  71. connection_error,
  72. ". Check if server is reachable at ",
  73. WebsocketTargetURL.create(),
  74. ]
  75. class ConnectionToaster(Toaster):
  76. """A connection toaster component."""
  77. def add_hooks(self) -> list[str | Var]:
  78. """Add the hooks for the connection toaster.
  79. Returns:
  80. The hooks for the connection toaster.
  81. """
  82. toast_id = "websocket-error"
  83. target_url = WebsocketTargetURL.create()
  84. props = ToastProps(
  85. description=LiteralVar.create(
  86. f"Check if server is reachable at {target_url}",
  87. ),
  88. close_button=True,
  89. duration=120000,
  90. id=toast_id,
  91. ) # pyright: ignore [reportCallIssue]
  92. individual_hooks = [
  93. f"const toast_props = {LiteralVar.create(props)!s};",
  94. "const [userDismissed, setUserDismissed] = useState(false);",
  95. FunctionStringVar(
  96. "useEffect",
  97. _var_data=VarData(
  98. imports={
  99. "react": ["useEffect", "useState"],
  100. **dict(target_url._get_all_var_data().imports), # pyright: ignore [reportArgumentType, reportOptionalMemberAccess]
  101. }
  102. ),
  103. ).call(
  104. # TODO: This breaks the assumption that Vars are JS expressions
  105. Var(
  106. _js_expr=f"""
  107. () => {{
  108. if ({has_too_many_connection_errors!s}) {{
  109. if (!userDismissed) {{
  110. toast.error(
  111. `Cannot connect to server: ${{{connection_error}}}.`,
  112. {{...toast_props, onDismiss: () => setUserDismissed(true)}},
  113. )
  114. }}
  115. }} else {{
  116. toast.dismiss("{toast_id}");
  117. setUserDismissed(false); // after reconnection reset dismissed state
  118. }}
  119. }}
  120. """
  121. ),
  122. LiteralArrayVar.create([connect_errors]),
  123. ),
  124. ]
  125. return [
  126. Hooks.EVENTS,
  127. *individual_hooks,
  128. ]
  129. @classmethod
  130. def create(cls, *children, **props) -> Component:
  131. """Create a connection toaster component.
  132. Args:
  133. *children: The children of the component.
  134. **props: The properties of the component.
  135. Returns:
  136. The connection toaster component.
  137. """
  138. Toaster.is_used = True
  139. return super().create(*children, **props)
  140. class ConnectionBanner(Component):
  141. """A connection banner component."""
  142. @classmethod
  143. def create(cls, comp: Optional[Component] = None) -> Component:
  144. """Create a connection banner component.
  145. Args:
  146. comp: The component to render when there's a server connection error.
  147. Returns:
  148. The connection banner component.
  149. """
  150. if not comp:
  151. comp = Flex.create(
  152. Text.create(
  153. *default_connection_error(),
  154. color="black",
  155. size="4",
  156. ),
  157. justify="center",
  158. background_color="crimson",
  159. width="100vw",
  160. padding="5px",
  161. position="fixed",
  162. )
  163. return cond(has_connection_errors, comp)
  164. class ConnectionModal(Component):
  165. """A connection status modal window."""
  166. @classmethod
  167. def create(cls, comp: Optional[Component] = None) -> Component:
  168. """Create a connection banner component.
  169. Args:
  170. comp: The component to render when there's a server connection error.
  171. Returns:
  172. The connection banner component.
  173. """
  174. if not comp:
  175. comp = Text.create(*default_connection_error())
  176. return 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. class WifiOffPulse(Icon):
  188. """A wifi_off icon with an animated opacity pulse."""
  189. @classmethod
  190. def create(cls, *children, **props) -> Icon:
  191. """Create a wifi_off icon with an animated opacity pulse.
  192. Args:
  193. *children: The children of the component.
  194. **props: The properties of the component.
  195. Returns:
  196. The icon component with default props applied.
  197. """
  198. pulse_var = Var(_js_expr="pulse")
  199. return super().create(
  200. "wifi_off",
  201. color=props.pop("color", "crimson"),
  202. size=props.pop("size", 32),
  203. z_index=props.pop("z_index", 9999),
  204. position=props.pop("position", "fixed"),
  205. bottom=props.pop("bottom", "33px"),
  206. right=props.pop("right", "33px"),
  207. animation=LiteralVar.create(f"{pulse_var} 1s infinite"),
  208. **props,
  209. )
  210. def add_imports(self) -> dict[str, str | ImportVar | list[str | ImportVar]]:
  211. """Add imports for the WifiOffPulse component.
  212. Returns:
  213. The import dict.
  214. """
  215. return {"@emotion/react": [ImportVar(tag="keyframes")]}
  216. def _get_custom_code(self) -> str | None:
  217. return """
  218. const pulse = keyframes`
  219. 0% {
  220. opacity: 0;
  221. }
  222. 100% {
  223. opacity: 1;
  224. }
  225. `
  226. """
  227. class ConnectionPulser(Div):
  228. """A connection pulser component."""
  229. @classmethod
  230. def create(cls, **props) -> Component:
  231. """Create a connection pulser component.
  232. Args:
  233. **props: The properties of the component.
  234. Returns:
  235. The connection pulser component.
  236. """
  237. return super().create(
  238. cond(
  239. has_connection_errors,
  240. WifiOffPulse.create(**props),
  241. ),
  242. title=f"Connection Error: {connection_error}",
  243. position="fixed",
  244. width="100vw",
  245. height="0",
  246. )
  247. class BackendDisabled(Div):
  248. """A component that displays a message when the backend is disabled."""
  249. @classmethod
  250. def create(cls, **props) -> Component:
  251. """Create a backend disabled component.
  252. Args:
  253. **props: The properties of the component.
  254. Returns:
  255. The backend disabled component.
  256. """
  257. import reflex as rx
  258. is_backend_disabled = Var(
  259. "backendDisabled",
  260. _var_type=bool,
  261. _var_data=VarData(
  262. hooks={
  263. "const [backendDisabled, setBackendDisabled] = useState(false);": None,
  264. "useEffect(() => { setBackendDisabled(isBackendDisabled()); }, []);": None,
  265. },
  266. imports={
  267. f"$/{constants.Dirs.STATE_PATH}": [
  268. ImportVar(tag="isBackendDisabled")
  269. ],
  270. },
  271. ),
  272. )
  273. return super().create(
  274. rx.cond(
  275. is_backend_disabled,
  276. rx.box(
  277. rx.box(
  278. rx.card(
  279. rx.vstack(
  280. svg_logo(),
  281. rx.text(
  282. "You ran out of compute credits.",
  283. ),
  284. rx.callout(
  285. rx.fragment(
  286. "Please upgrade your plan or raise your compute credits at ",
  287. rx.link(
  288. "Reflex Cloud.",
  289. href="https://cloud.reflex.dev/",
  290. ),
  291. ),
  292. width="100%",
  293. icon="info",
  294. variant="surface",
  295. ),
  296. ),
  297. font_size="20px",
  298. font_family='"Inter", "Helvetica", "Arial", sans-serif',
  299. variant="classic",
  300. ),
  301. position="fixed",
  302. top="50%",
  303. left="50%",
  304. transform="translate(-50%, -50%)",
  305. width="40ch",
  306. max_width="90vw",
  307. ),
  308. position="fixed",
  309. z_index=9999,
  310. backdrop_filter="grayscale(1) blur(5px)",
  311. width="100dvw",
  312. height="100dvh",
  313. ),
  314. )
  315. )
  316. connection_banner = ConnectionBanner.create
  317. connection_modal = ConnectionModal.create
  318. connection_toaster = ConnectionToaster.create
  319. connection_pulser = ConnectionPulser.create
  320. backend_disabled = BackendDisabled.create