toast.py 12 KB

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