toast.py 11 KB

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