Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/library/overlay/toast.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ The following props are available for customization:
- `id`: `str | Var`: Custom id for the toast.
- `unstyled`: `bool`: Removes the default styling, which allows for easier customization.
- `style`: `Style`: Custom style for the toast.
- `action_button_style`: `Style`: Custom style for the button that `action` renders.
- `cancel_button_style`: `Style`: Custom style for the button that `cancel` renders.
- `on_dismiss`: `Any`: The function gets called when either the close button is clicked, or the toast is swiped.
- `on_auto_close`: `Any`: Function that gets called when the toast disappears automatically after it's timeout (`duration` prop).

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Deprecate the `action_button_styles` and `cancel_button_styles` toast props in favor of `action_button_style` and `cancel_button_style`, which match Sonner's option names. Passing the plural names to `rx.toast(...)` or `rx.toast.options(...)` keeps working with a deprecation warning until Reflex 1.0. If both names are passed for the same button, the singular one is used.

```python
# deprecated
rx.toast("Saved", action=..., action_button_styles={"background_color": "red"})

# supported
rx.toast("Saved", action=..., action_button_style={"background_color": "red"})
```
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from reflex_base.constants.base import Dirs
from reflex_base.event import EventSpec, run_script
from reflex_base.style import Style, resolved_color_mode
from reflex_base.utils import format
from reflex_base.utils import console, format
from reflex_base.utils.imports import ImportVar
from reflex_base.utils.serializers import serializer
from reflex_base.vars import VarData
Expand All @@ -35,9 +35,10 @@
_var_data=VarData(imports={f"$/{Dirs.STATE_PATH}": [ImportVar(tag="refs")]}),
)

_TOAST_STYLE_PROP_ALIASES = (
("actionButtonStyles", "actionButtonStyle"),
("cancelButtonStyles", "cancelButtonStyle"),
# Deprecated button style prop names and their replacements. Remove in 1.0.
_DEPRECATED_BUTTON_STYLE_PROPS = (
("action_button_styles", "action_button_style"),
("cancel_button_styles", "cancel_button_style"),
)


Expand Down Expand Up @@ -130,9 +131,16 @@ class ToastProps(NoExtrasAllowedProps):
# Class name for the toast.
class_name: str | None

action_button_styles: Style | None
# Custom style for the toast primary button.
action_button_style: Style | None

# Custom style for the toast secondary button.
cancel_button_style: Style | None

# Deprecated, use `action_button_style`.
action_button_styles: Style | None

# Deprecated, use `cancel_button_style`.
cancel_button_styles: Style | None

# The function gets called when either the close button is clicked, or the toast is swiped.
Expand All @@ -141,6 +149,27 @@ class ToastProps(NoExtrasAllowedProps):
# Function that gets called when the toast disappears automatically after it's timeout (duration` prop).
on_auto_close: Any | None

def __init__(self, component_name: str | None = None, **kwargs: Any):
"""Initialize the toast props, moving deprecated prop names to their replacements.

If a deprecated name and its replacement are both passed, the replacement is used.

Args:
component_name: The custom name of the component.
**kwargs: Kwargs to initialize the props.
"""
for deprecated_name, name in _DEPRECATED_BUTTON_STYLE_PROPS:
if deprecated_name not in kwargs:
continue
console.deprecate(
feature_name=f"The `{deprecated_name}` toast prop",
reason=f"Use `{name}` instead, which matches Sonner's option name",
deprecation_version="0.11.1",
removal_version="1.0",
)
kwargs.setdefault(name, kwargs.pop(deprecated_name))
super().__init__(component_name=component_name, **kwargs)

def dict(self, *args: Any, **kwargs: Any) -> builtins.dict[str, Any]:
"""Convert the object to a dictionary.

Expand All @@ -152,9 +181,6 @@ def dict(self, *args: Any, **kwargs: Any) -> builtins.dict[str, Any]:
The object as a dictionary with ToastAction fields intact.
"""
d = super().dict(*args, **kwargs)
for reflex_name, sonner_name in _TOAST_STYLE_PROP_ALIASES:
if reflex_name in d:
d[sonner_name] = d.pop(reflex_name)
# Keep these fields as ToastAction so they can be serialized specially
if "action" in d:
d["action"] = self.action
Expand Down
2 changes: 1 addition & 1 deletion pyi_hashes.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
"packages/reflex-components-recharts/src/reflex_components_recharts/general.pyi": "fe22b3cf69e9ae3d425cc88c3511525b",
"packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "adc4db1a3ca7cd292b099ec4d97a4346",
"packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "f2a9cf6db58d169289fbc76de6813300",
"packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "b195e3845260389ced026d2f5c4adb93",
"packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "113231e807bb4fb013962fa8b1e1aa0b",
"reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a",
"reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388",
"reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e"
Expand Down
94 changes: 85 additions & 9 deletions tests/units/reflex_components_sonner/test_toast.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,103 @@
"""Sonner toast component tests."""

import json
from unittest.mock import call

from pytest_mock import MockerFixture
from reflex_base.style import Style
from reflex_components_sonner.toast import Toaster, ToastProps

_DEPRECATION_CALLS = [
call(
feature_name="The `action_button_styles` toast prop",
reason="Use `action_button_style` instead, which matches Sonner's option name",
deprecation_version="0.11.1",
removal_version="1.0",
),
call(
feature_name="The `cancel_button_styles` toast prop",
reason="Use `cancel_button_style` instead, which matches Sonner's option name",
deprecation_version="0.11.1",
removal_version="1.0",
),
]


def test_toaster_hotkey_accepts_key_list():
"""Sonner reads `hotkey` as an array of KeyboardEvent keys and codes."""
toaster = Toaster.create(hotkey=["altKey", "KeyT"])
assert 'hotkey:["altKey", "KeyT"]' in str(toaster)


def test_toast_button_styles_use_sonner_prop_names():
"""Serialize toast button styles with Sonner's singular option names."""
def test_toast_button_styles_use_sonner_prop_names(mocker: MockerFixture):
"""The button style props serialize to Sonner's option names as they are."""
deprecate = mocker.patch("reflex_base.utils.console.deprecate")
props = ToastProps(
action_button_styles=Style({"background_color": "red"}),
cancel_button_styles=Style({"color": "white"}),
action_button_style=Style({"background_color": "red"}),
cancel_button_style=Style({"color": "white"}),
) # pyright: ignore[reportCallIssue]

serialized = json.loads(props.json())
deprecate.assert_not_called()
assert json.loads(props.json()) == {
"actionButtonStyle": {"backgroundColor": "red"},
"cancelButtonStyle": {"color": "white"},
}


def test_toast_deprecated_button_styles(mocker: MockerFixture):
"""The plural names still work, warn, and serialize like the singular ones."""
deprecate = mocker.patch("reflex_base.utils.console.deprecate")
action_style = Style({"background_color": "red"})
cancel_style = Style({"color": "white"})
props = ToastProps(
Comment thread
zeyadrabie marked this conversation as resolved.
Resolved
action_button_styles=action_style,
cancel_button_styles=cancel_style,
) # pyright: ignore[reportCallIssue]

assert deprecate.call_args_list == _DEPRECATION_CALLS
assert props.action_button_style is action_style
assert props.cancel_button_style is cancel_style
assert props.action_button_styles is None
assert props.cancel_button_styles is None
assert json.loads(props.json()) == {
"actionButtonStyle": {"backgroundColor": "red"},
"cancelButtonStyle": {"color": "white"},
}


def test_toast_button_style_wins_over_deprecated_name(mocker: MockerFixture):
"""With both names passed, the singular one is used and the plural one only warns."""
deprecate = mocker.patch("reflex_base.utils.console.deprecate")
action_style = Style({"color": "red"})
cancel_style = Style({"color": "white"})
props = ToastProps(
action_button_style=action_style,
action_button_styles=Style({"color": "blue"}),
cancel_button_style=cancel_style,
cancel_button_styles=Style({"color": "black"}),
) # pyright: ignore[reportCallIssue]

assert deprecate.call_args_list == _DEPRECATION_CALLS
assert props.action_button_style is action_style
assert props.cancel_button_style is cancel_style
assert props.action_button_styles is None
assert props.cancel_button_styles is None
assert json.loads(props.json()) == {
"actionButtonStyle": {"color": "red"},
"cancelButtonStyle": {"color": "white"},
}


def test_toaster_toast_options_button_styles():
"""Default toast options passed to the provider carry Sonner's option names."""
toaster = Toaster.create(
toast_options=ToastProps(
action_button_style=Style({"background_color": "red"}),
cancel_button_style=Style({"color": "white"}),
) # pyright: ignore[reportCallIssue]
)

assert serialized["actionButtonStyle"]["backgroundColor"] == "red"
assert serialized["cancelButtonStyle"]["color"] == "white"
assert "actionButtonStyles" not in serialized
assert "cancelButtonStyles" not in serialized
assert str(toaster.toast_options) == ( # pyright: ignore[reportAttributeAccessIssue]
'({ ["actionButtonStyle"] : ({ ["backgroundColor"] : "red" }), '
'["cancelButtonStyle"] : ({ ["color"] : "white" }) })'
)
Loading