toast.py 11 KB

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