toast.py 11 KB

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