diff --git a/packages/reflex-components-sonner/news/+8017-toast-dismiss-string-id.bugfix.md b/packages/reflex-components-sonner/news/+8017-toast-dismiss-string-id.bugfix.md new file mode 100644 index 00000000000..1340595184b --- /dev/null +++ b/packages/reflex-components-sonner/news/+8017-toast-dismiss-string-id.bugfix.md @@ -0,0 +1 @@ +Toast IDs passed to ``rx.toast.dismiss`` are now serialized safely when they contain quotes or newlines. diff --git a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py index ff6bece4b13..2d5e073bec1 100644 --- a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py +++ b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py @@ -4,6 +4,7 @@ import builtins import dataclasses +import json from typing import Any, Literal from reflex_base.components.component import Component, ComponentNamespace, field @@ -382,7 +383,9 @@ def toast_dismiss(id: Var[str] | str | None = None) -> EventSpec: dismiss = f"{toast_ref}.dismiss({id!s})" dismiss_var_data = id._get_all_var_data() elif isinstance(id, str): - dismiss = f"{toast_ref}.dismiss('{id}')" + # Escape marker syntax before the Var decoder sees the expression. + serialized_id = json.dumps(id).replace("<", r"\u003c") + dismiss = f"{toast_ref}.dismiss({serialized_id})" else: dismiss = f"{toast_ref}.dismiss()" dismiss_action = Var( diff --git a/tests/units/reflex_components_sonner/test_toast.py b/tests/units/reflex_components_sonner/test_toast.py index bca21a536ed..6b1c42a32f8 100644 --- a/tests/units/reflex_components_sonner/test_toast.py +++ b/tests/units/reflex_components_sonner/test_toast.py @@ -2,6 +2,7 @@ import json +import pytest from reflex_base.style import Style from reflex_components_sonner.toast import Toaster, ToastProps @@ -25,3 +26,37 @@ def test_toast_button_styles_use_sonner_prop_names(): assert serialized["cancelButtonStyle"]["color"] == "white" assert "actionButtonStyles" not in serialized assert "cancelButtonStyles" not in serialized + + +@pytest.mark.parametrize( + ("toast_id", "expected"), + [ + ( + "toast's-id", + """(() => refs['__toast'].dismiss("toast's-id"))""", + ), + ( + 'toast"-id', + r"""(() => refs['__toast'].dismiss("toast\"-id"))""", + ), + ( + "toast\nid", + r"""(() => refs['__toast'].dismiss("toast\nid"))""", + ), + ( + "x", + r"""(() => refs['__toast'].dismiss("\u003creflex.Var>x\u003c/reflex.Var>"))""", + ), + ], +) +def test_toast_dismiss_serializes_string_id(toast_id: str, expected: str) -> None: + """Serialize string IDs as opaque JavaScript string literals. + + Args: + toast_id: The string to pass to the dismissal handler. + expected: The complete generated JavaScript function. + """ + event = Toaster.toast_dismiss(toast_id) + function = next(value for key, value in event.args if str(key) == "function") + + assert str(function) == expected