toast.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. """Sonner toast component."""
  2. from __future__ import annotations
  3. from typing import Any, ClassVar, Literal, Optional, Union
  4. from reflex.base import Base
  5. from reflex.components.component import Component, ComponentNamespace
  6. from reflex.components.lucide.icon import Icon
  7. from reflex.components.props import NoExtrasAllowedProps, PropsBase
  8. from reflex.constants.base import Dirs
  9. from reflex.event import EventSpec, run_script
  10. from reflex.style import Style, resolved_color_mode
  11. from reflex.utils import format
  12. from reflex.utils.imports import ImportVar
  13. from reflex.utils.serializers import serializer
  14. from reflex.vars import VarData
  15. from reflex.vars.base import LiteralVar, Var
  16. from reflex.vars.function import FunctionVar
  17. from reflex.vars.object import ObjectVar
  18. LiteralPosition = Literal[
  19. "top-left",
  20. "top-center",
  21. "top-right",
  22. "bottom-left",
  23. "bottom-center",
  24. "bottom-right",
  25. ]
  26. toast_ref = Var(
  27. _js_expr="refs['__toast']",
  28. _var_data=VarData(imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}),
  29. )
  30. class ToastAction(Base):
  31. """A toast action that render a button in the toast."""
  32. label: str
  33. on_click: Any
  34. @serializer
  35. def serialize_action(action: ToastAction) -> dict:
  36. """Serialize a toast action.
  37. Args:
  38. action: The toast action to serialize.
  39. Returns:
  40. The serialized toast action with on_click formatted to queue the given event.
  41. """
  42. return {
  43. "label": action.label,
  44. "onClick": format.format_queue_events(action.on_click),
  45. }
  46. def _toast_callback_signature(toast: Var) -> list[Var]:
  47. """The signature for the toast callback, stripping out unserializable keys.
  48. Args:
  49. toast: The toast variable.
  50. Returns:
  51. A function call stripping non-serializable members of the toast object.
  52. """
  53. return [
  54. Var(
  55. _js_expr=f"(() => {{let {{action, cancel, onDismiss, onAutoClose, ...rest}} = {toast!s}; return rest}})()"
  56. )
  57. ]
  58. class ToastProps(PropsBase, NoExtrasAllowedProps):
  59. """Props for the toast component."""
  60. # Toast's title, renders above the description.
  61. title: Optional[Union[str, Var]]
  62. # Toast's description, renders underneath the title.
  63. description: Optional[Union[str, Var]]
  64. # Whether to show the close button.
  65. close_button: Optional[bool]
  66. # Dark toast in light mode and vice versa.
  67. invert: Optional[bool]
  68. # Control the sensitivity of the toast for screen readers
  69. important: Optional[bool]
  70. # Time in milliseconds that should elapse before automatically closing the toast.
  71. duration: Optional[int]
  72. # Position of the toast.
  73. position: Optional[LiteralPosition]
  74. # If false, it'll prevent the user from dismissing the toast.
  75. dismissible: Optional[bool]
  76. # TODO: fix serialization of icons for toast? (might not be possible yet)
  77. # Icon displayed in front of toast's text, aligned vertically.
  78. # icon: Optional[Icon] = None # noqa: ERA001
  79. # TODO: fix implementation for action / cancel buttons
  80. # Renders a primary button, clicking it will close the toast.
  81. action: Optional[ToastAction]
  82. # Renders a secondary button, clicking it will close the toast.
  83. cancel: Optional[ToastAction]
  84. # Custom id for the toast.
  85. id: Optional[Union[str, Var]]
  86. # Removes the default styling, which allows for easier customization.
  87. unstyled: Optional[bool]
  88. # Custom style for the toast.
  89. style: Optional[Style]
  90. # Class name for the toast.
  91. class_name: Optional[str]
  92. # XXX: These still do not seem to work
  93. # Custom style for the toast primary button.
  94. action_button_styles: Optional[Style]
  95. # Custom style for the toast secondary button.
  96. cancel_button_styles: Optional[Style]
  97. # The function gets called when either the close button is clicked, or the toast is swiped.
  98. on_dismiss: Optional[Any]
  99. # Function that gets called when the toast disappears automatically after it's timeout (duration` prop).
  100. on_auto_close: Optional[Any]
  101. def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
  102. """Convert the object to a dictionary.
  103. Args:
  104. *args: The arguments to pass to the base class.
  105. **kwargs: The keyword arguments to pass to the base
  106. Returns:
  107. The object as a dictionary with ToastAction fields intact.
  108. """
  109. kwargs.setdefault("exclude_none", True)
  110. d = super().dict(*args, **kwargs)
  111. # Keep these fields as ToastAction so they can be serialized specially
  112. if "action" in d:
  113. d["action"] = self.action
  114. if isinstance(self.action, dict):
  115. d["action"] = ToastAction(**self.action)
  116. if "cancel" in d:
  117. d["cancel"] = self.cancel
  118. if isinstance(self.cancel, dict):
  119. d["cancel"] = ToastAction(**self.cancel)
  120. if "onDismiss" in d:
  121. d["onDismiss"] = format.format_queue_events(
  122. self.on_dismiss, _toast_callback_signature
  123. )
  124. if "onAutoClose" in d:
  125. d["onAutoClose"] = format.format_queue_events(
  126. self.on_auto_close, _toast_callback_signature
  127. )
  128. return d
  129. class Toaster(Component):
  130. """A Toaster Component for displaying toast notifications."""
  131. library: str | None = "sonner@1.7.2"
  132. tag = "Toaster"
  133. # the theme of the toast
  134. theme: Var[str] = resolved_color_mode
  135. # whether to show rich colors
  136. rich_colors: Var[bool] = LiteralVar.create(True)
  137. # whether to expand the toast
  138. expand: Var[bool] = LiteralVar.create(True)
  139. # the number of toasts that are currently visible
  140. visible_toasts: Var[int]
  141. # the position of the toast
  142. position: Var[LiteralPosition] = LiteralVar.create("bottom-right")
  143. # whether to show the close button
  144. close_button: Var[bool] = LiteralVar.create(False)
  145. # offset of the toast
  146. offset: Var[str]
  147. # directionality of the toast (default: ltr)
  148. dir: Var[str]
  149. # Keyboard shortcut that will move focus to the toaster area.
  150. hotkey: Var[str]
  151. # Dark toasts in light mode and vice versa.
  152. invert: Var[bool]
  153. # These will act as default options for all toasts. See toast() for all available options.
  154. toast_options: Var[ToastProps]
  155. # Gap between toasts when expanded
  156. gap: Var[int]
  157. # Changes the default loading icon
  158. loading_icon: Var[Icon]
  159. # Pauses toast timers when the page is hidden, e.g., when the tab is backgrounded, the browser is minimized, or the OS is locked.
  160. pause_when_page_is_hidden: Var[bool]
  161. # Marked True when any Toast component is created.
  162. is_used: ClassVar[bool] = False
  163. def add_hooks(self) -> list[Var | str]:
  164. """Add hooks for the toaster component.
  165. Returns:
  166. The hooks for the toaster component.
  167. """
  168. if self.library is None:
  169. return []
  170. hook = Var(
  171. _js_expr=f"{toast_ref} = toast",
  172. _var_data=VarData(
  173. imports={
  174. "$/utils/state": [ImportVar(tag="refs")],
  175. self.library: [ImportVar(tag="toast", install=False)],
  176. }
  177. ),
  178. )
  179. return [hook]
  180. @staticmethod
  181. def send_toast(
  182. message: str | Var = "", level: str | None = None, **props
  183. ) -> EventSpec:
  184. """Send a toast message.
  185. Args:
  186. message: The message to display.
  187. level: The level of the toast.
  188. **props: The options for the toast.
  189. Raises:
  190. ValueError: If the Toaster component is not created.
  191. Returns:
  192. The toast event.
  193. """
  194. if not Toaster.is_used:
  195. raise ValueError(
  196. "Toaster component must be created before sending a toast. (use `rx.toast.provider()`)"
  197. )
  198. toast_command = (
  199. ObjectVar.__getattr__(toast_ref.to(dict), level) if level else toast_ref
  200. ).to(FunctionVar)
  201. if isinstance(message, Var):
  202. props.setdefault("title", message)
  203. message = ""
  204. elif message == "" and "title" not in props and "description" not in props:
  205. raise ValueError("Toast message or title or description must be provided.")
  206. if props:
  207. args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # pyright: ignore [reportCallIssue]
  208. toast = toast_command.call(message, args)
  209. else:
  210. toast = toast_command.call(message)
  211. return run_script(toast)
  212. @staticmethod
  213. def toast_info(message: str | Var = "", **kwargs: Any):
  214. """Display an info toast message.
  215. Args:
  216. message: The message to display.
  217. **kwargs: Additional toast props.
  218. Returns:
  219. The toast event.
  220. """
  221. return Toaster.send_toast(message, level="info", **kwargs)
  222. @staticmethod
  223. def toast_warning(message: str | Var = "", **kwargs: Any):
  224. """Display a warning toast message.
  225. Args:
  226. message: The message to display.
  227. **kwargs: Additional toast props.
  228. Returns:
  229. The toast event.
  230. """
  231. return Toaster.send_toast(message, level="warning", **kwargs)
  232. @staticmethod
  233. def toast_error(message: str | Var = "", **kwargs: Any):
  234. """Display an error toast message.
  235. Args:
  236. message: The message to display.
  237. **kwargs: Additional toast props.
  238. Returns:
  239. The toast event.
  240. """
  241. return Toaster.send_toast(message, level="error", **kwargs)
  242. @staticmethod
  243. def toast_success(message: str | Var = "", **kwargs: Any):
  244. """Display a success toast message.
  245. Args:
  246. message: The message to display.
  247. **kwargs: Additional toast props.
  248. Returns:
  249. The toast event.
  250. """
  251. return Toaster.send_toast(message, level="success", **kwargs)
  252. @staticmethod
  253. def toast_loading(message: str | Var = "", **kwargs: Any):
  254. """Display a loading toast message.
  255. Args:
  256. message: The message to display.
  257. **kwargs: Additional toast props.
  258. Returns:
  259. The toast event.
  260. """
  261. return Toaster.send_toast(message, level="loading", **kwargs)
  262. @staticmethod
  263. def toast_dismiss(id: Var | str | None = None):
  264. """Dismiss a toast.
  265. Args:
  266. id: The id of the toast to dismiss.
  267. Returns:
  268. The toast dismiss event.
  269. """
  270. dismiss_var_data = None
  271. if isinstance(id, Var):
  272. dismiss = f"{toast_ref}.dismiss({id!s})"
  273. dismiss_var_data = id._get_all_var_data()
  274. elif isinstance(id, str):
  275. dismiss = f"{toast_ref}.dismiss('{id}')"
  276. else:
  277. dismiss = f"{toast_ref}.dismiss()"
  278. dismiss_action = Var(
  279. _js_expr=dismiss, _var_data=VarData.merge(dismiss_var_data)
  280. )
  281. return run_script(dismiss_action)
  282. @classmethod
  283. def create(cls, *children: Any, **props: Any) -> Component:
  284. """Create a toaster component.
  285. Args:
  286. *children: The children of the toaster.
  287. **props: The properties of the toaster.
  288. Returns:
  289. The toaster component.
  290. """
  291. cls.is_used = True
  292. return super().create(*children, **props)
  293. # TODO: figure out why loading toast stay open forever when using level="loading" in toast()
  294. class ToastNamespace(ComponentNamespace):
  295. """Namespace for toast components."""
  296. provider = staticmethod(Toaster.create)
  297. options = staticmethod(ToastProps)
  298. info = staticmethod(Toaster.toast_info)
  299. warning = staticmethod(Toaster.toast_warning)
  300. error = staticmethod(Toaster.toast_error)
  301. success = staticmethod(Toaster.toast_success)
  302. loading = staticmethod(Toaster.toast_loading)
  303. dismiss = staticmethod(Toaster.toast_dismiss)
  304. __call__ = staticmethod(Toaster.send_toast)
  305. toast = ToastNamespace()