diff --git a/docs/pages/dynamic_routing.md b/docs/pages/dynamic_routing.md index 5484c0e3323..ed6b1a30611 100644 --- a/docs/pages/dynamic_routing.md +++ b/docs/pages/dynamic_routing.md @@ -18,14 +18,21 @@ Regular dynamic routes in Reflex allow you to match specific segments in a URL d The dynamic route arguments are accessible as `rx.State.id` and `rx.State.category` here as the var is added to the root state, so that it is accessible from any state. ``` +```md alert info +# Accessing a dynamic route argument with type checking + +The var is added to the root state when the page is added, so type checkers do not know `rx.State.id`. `rx.route_arg("id")` returns the same var as a `StringVar`. Like `rx.State.id`, it is a var for building components, not the value: an event handler or a computed var reads the value from the state as before. +``` + Example: ```python @rx.page(route="/post/[pid]") def post(): """A page that updates based on the route.""" - # Displays the dynamic part of the URL, the post ID - return rx.heading(rx.State.pid, as_="h2") + # Displays the dynamic part of the URL, the post ID. `rx.route_arg("pid")` + # is `rx.State.pid`, typed. + return rx.heading(rx.route_arg("pid"), as_="h2") app = rx.App() @@ -83,6 +90,14 @@ app = rx.App() In this case, the `...splat` catch-all pattern captures any number of segments after `/users/`, allowing URLs like `/users/2/posts/john/` and `/users/1/posts/john/doe/` to match the route. +`rx.route_catch_all()` returns the catch-all var, `rx.State.splat`, as an `ArrayVar[list[str]]`. Like `rx.route_arg`, it is a var for building components, not the value: + +```python +@rx.page(route="/files/[[...splat]]") +def files(): + return rx.vstack(rx.foreach(rx.route_catch_all(), rx.text)) +``` + ```md alert # Catch-all routes must be named `splat` and be placed at the end of the URL pattern to ensure proper route matching. ``` diff --git a/news/+typed-route-arg.feature.md b/news/+typed-route-arg.feature.md new file mode 100644 index 00000000000..425f879d462 --- /dev/null +++ b/news/+typed-route-arg.feature.md @@ -0,0 +1 @@ +Add `rx.route_arg(name)` and `rx.route_catch_all()`, which return the var of a page's dynamic route argument with a type that type checkers see, unlike `rx.State.name`: a `StringVar` for `[name]` and an `ArrayVar[list[str]]` for the `[[...splat]]` catch-all, for example `rx.heading(rx.route_arg("pid"))` on a page at `/post/[pid]`. diff --git a/packages/reflex-base/news/+typed-route-arg.feature.md b/packages/reflex-base/news/+typed-route-arg.feature.md new file mode 100644 index 00000000000..90c7a7f6d05 --- /dev/null +++ b/packages/reflex-base/news/+typed-route-arg.feature.md @@ -0,0 +1 @@ +Add `DynamicRouteArgNotFoundError`, raised by `rx.route_arg` and `rx.route_catch_all` for a dynamic route argument that no page added so far has as that kind. diff --git a/packages/reflex-base/src/reflex_base/constants/route.py b/packages/reflex-base/src/reflex_base/constants/route.py index 4c8606561eb..cdf76b69e38 100644 --- a/packages/reflex-base/src/reflex_base/constants/route.py +++ b/packages/reflex-base/src/reflex_base/constants/route.py @@ -82,7 +82,9 @@ class RouteRegex(SimpleNamespace): rf"{_OPENING_BRACKET * 2}{_DOT_DOT_DOT}({_ARG_NAME}){_CLOSING_BRACKET * 2}" ) - SPLAT_CATCHALL = "[[...splat]]" + # The name of the catch-all arg, and the only catch-all pattern allowed. + SPLAT_ARG = "splat" + SPLAT_CATCHALL = f"[[...{SPLAT_ARG}]]" SINGLE_SEGMENT = "__SINGLE_SEGMENT__" DOUBLE_SEGMENT = "__DOUBLE_SEGMENT__" DOUBLE_CATCHALL_SEGMENT = "__DOUBLE_CATCHALL_SEGMENT__" diff --git a/packages/reflex-base/src/reflex_base/utils/exceptions.py b/packages/reflex-base/src/reflex_base/utils/exceptions.py index 75368add0eb..9f13a982d0b 100644 --- a/packages/reflex-base/src/reflex_base/utils/exceptions.py +++ b/packages/reflex-base/src/reflex_base/utils/exceptions.py @@ -214,6 +214,10 @@ class DynamicRouteArgShadowsStateVarError(ReflexError, NameError): """Raised when a dynamic route arg shadows a state var.""" +class DynamicRouteArgNotFoundError(ReflexError, AttributeError): + """Raised when a dynamic route arg is requested that no added page declares as such.""" + + class ComputedVarShadowsStateVarError(ReflexError, NameError): """Raised when a computed var shadows a state var.""" diff --git a/pyi_hashes.json b/pyi_hashes.json index 8f2b4c8aa7a..c171bd3b004 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -118,7 +118,7 @@ "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": "f170ac685b6ba5892370166c80684db3", - "reflex/__init__.pyi": "067a60e22fb825072f2f0b690662da5a", + "reflex/__init__.pyi": "d14b41f4d9f0ccf5c14fcf56dbaf8c21", "reflex/components/__init__.pyi": "9facd05a776d0641432696bbf8e34388", "reflex/experimental/memo.pyi": "0fc8eae24cd0def5ea9d8d66ce87206e" } diff --git a/reflex/__init__.py b/reflex/__init__.py index 75cb5a1328b..a663fdb6b92 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -221,6 +221,8 @@ "ComponentState", "State", "dynamic", + "route_arg", + "route_catch_all", ], "istate.shared": ["SharedState"], "istate.wrappers": ["get_state"], diff --git a/reflex/route.py b/reflex/route.py index cfed5aa55d8..dd0a5612b4d 100644 --- a/reflex/route.py +++ b/reflex/route.py @@ -80,7 +80,7 @@ def _add_route_arg(arg_name: str, type_: str): # Iterate over the route parts and check for route args. for part in route.split("/"): if part == constants.RouteRegex.SPLAT_CATCHALL: - _add_route_arg("splat", constants.RouteArgType.LIST) + _add_route_arg(constants.RouteRegex.SPLAT_ARG, constants.RouteArgType.LIST) break optional_argument = optional_argument_regex.match(part) diff --git a/reflex/state.py b/reflex/state.py index 51934fe3e97..3caf7abf256 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -48,6 +48,7 @@ from reflex_base.registry import RegistrationContext from reflex_base.utils.exceptions import ( DynamicComponentInvalidSignatureError, + DynamicRouteArgNotFoundError, DynamicRouteArgShadowsStateVarError, ReflexRuntimeError, SetUndefinedStateVarError, @@ -140,6 +141,7 @@ def _stale_pickle_keys(cls: type[BaseState]) -> frozenset[str]: if TYPE_CHECKING: from reflex_base.components.component import Component + from reflex_base.vars.sequence import ArrayVar, StringVar var = computed_var @@ -417,6 +419,22 @@ def _bind_attr(cls: type, name: str, value: Any) -> None: value.__set_name__(cls, name) +def _route_arg_type(var: DynamicRouteVar) -> str: + """Get the route arg type a page installed a dynamic route var as. + + Args: + var: The dynamic route var. + + Returns: + ``RouteArgType.LIST`` for the catch-all, ``RouteArgType.SINGLE`` otherwise. + """ + return ( + constants.RouteArgType.LIST + if var._var_type == list[str] + else constants.RouteArgType.SINGLE + ) + + def _router_fget(self: BaseState) -> RouterData: """Assemble the RouterData view over the per-field router vars. @@ -1600,11 +1618,7 @@ def _dynamic_route_arg_types(cls) -> builtins.dict[str, str]: A mapping of dynamic route argument name to ``RouteArgType`` value. """ return { - name: ( - constants.RouteArgType.LIST - if computed_var._var_type == list[str] - else constants.RouteArgType.SINGLE - ) + name: _route_arg_type(computed_var) for name, computed_var in cls.computed_vars.items() if isinstance(computed_var, DynamicRouteVar) } @@ -3027,6 +3041,81 @@ def wrapper() -> Component: return wrapper +def _installed_route_arg(name: str) -> tuple[Any, str] | None: + """Get the var a page installed on ``rx.State`` for a dynamic route arg. + + Args: + name: The name of the dynamic route arg. + + Returns: + The var as class access returns it and its ``RouteArgType``, or None if + no page added so far has the arg. + """ + var = State.vars.get(name) + if not isinstance(var, DynamicRouteVar): + return None + return getattr(State, name), _route_arg_type(var) + + +def route_arg(name: str) -> StringVar: + """Get the var of a dynamic route arg, such as ``pid`` in ``/post/[pid]``. + + Adding the page installs the var ``rx.State.pid``, which type checkers cannot + see; this returns the same var, typed. Like ``rx.State.pid``, it is a var for + building components, not the value: an event handler or a computed var reads + the value from the state as before. The ``[[...splat]]`` catch-all is + ``route_catch_all()``. + + Args: + name: The name of the dynamic route arg, as in ``[name]`` or the + optional ``[[name]]``. + + Returns: + The var of the dynamic route arg. + + Raises: + DynamicRouteArgNotFoundError: If no page added so far has the arg, or the + arg is the catch-all. + """ + installed = _installed_route_arg(name) + if installed is None: + msg = f"No dynamic route arg `{name}` is installed: no page added so far has `[{name}]` in its route." + raise DynamicRouteArgNotFoundError(msg) + var, arg_type = installed + if arg_type != constants.RouteArgType.SINGLE: + msg = f"`{name}` is installed as the catch-all `{constants.RouteRegex.SPLAT_CATCHALL}`; use `rx.route_catch_all()` for it." + raise DynamicRouteArgNotFoundError(msg) + return var + + +def route_catch_all() -> ArrayVar[list[str]]: + """Get the var of the ``[[...splat]]`` catch-all route arg. + + Adding a page at ``/docs/[[...splat]]`` installs the var ``rx.State.splat`` + with the remaining path segments, which type checkers cannot see; this + returns the same var, typed. Like ``rx.State.splat``, it is a var for building + components, not the value: an event handler or a computed var reads the value + from the state as before. + + Returns: + The var of the catch-all route arg. + + Raises: + DynamicRouteArgNotFoundError: If no page added so far has the catch-all, + or ``splat`` is a regular dynamic route arg. + """ + name = constants.RouteRegex.SPLAT_ARG + installed = _installed_route_arg(name) + if installed is None: + msg = f"No catch-all route arg is installed: no page added so far has `{constants.RouteRegex.SPLAT_CATCHALL}` in its route." + raise DynamicRouteArgNotFoundError(msg) + var, arg_type = installed + if arg_type != constants.RouteArgType.LIST: + msg = f'`{name}` is installed as the regular dynamic route arg `[{name}]`; use `rx.route_arg("{name}")` for it.' + raise DynamicRouteArgNotFoundError(msg) + return var + + # sessionStorage key holding the ms timestamp of the last reload on error LAST_RELOADED_KEY = "reflex_last_reloaded_on_error" diff --git a/tests/type_checking/state.py b/tests/type_checking/state.py new file mode 100644 index 00000000000..158b74d531d --- /dev/null +++ b/tests/type_checking/state.py @@ -0,0 +1,12 @@ +"""Inferred types for `reflex.state` that are part of the public contract.""" + +from typing import assert_type + +import reflex as rx +from reflex.vars.sequence import ArrayVar, StringVar + +# `rx.State.pid` only exists once a page at `/post/[pid]` is added, so type +# checkers cannot see it; `rx.route_arg` returns the same var, typed, and +# `rx.route_catch_all` the one of a `[[...splat]]` catch-all. +assert_type(rx.route_arg("pid"), StringVar) +assert_type(rx.route_catch_all(), ArrayVar[list[str]]) diff --git a/tests/units/test_state.py b/tests/units/test_state.py index 4a516554069..8d32f09e568 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -41,6 +41,7 @@ from reflex_base.registry import RegistrationContext from reflex_base.utils import format, types from reflex_base.utils.exceptions import ( + DynamicRouteArgNotFoundError, EventHandlerValueError, InvalidLockWarningThresholdError, LockExpiredError, @@ -54,6 +55,7 @@ ) from reflex_base.utils.format import json_dumps from reflex_base.vars.base import Field, Var, computed_var, field +from reflex_base.vars.sequence import ArrayVar, StringVar from typing_extensions import TypeAliasType import reflex as rx @@ -74,6 +76,7 @@ from reflex.istate.manager.redis import StateManagerRedis from reflex.istate.manager.token import BaseStateToken from reflex.istate.proxy import MutableProxy, StateProxy +from reflex.route import get_route_args from reflex.state import ( BaseState, ImmutableStateError, @@ -4455,6 +4458,125 @@ def test_router_field_names_are_reserved(name): ) +@pytest.fixture +def route_arg_root(monkeypatch: pytest.MonkeyPatch) -> type[BaseState]: + """A fresh root state for `rx.route_arg` and `rx.route_catch_all` to resolve against. + + Route args installed on `rx.State` would stay for the rest of the session, + and one root cannot hold both a regular `[splat]` and the catch-all. + + Args: + monkeypatch: The pytest monkeypatch fixture. + + Returns: + The root state the accessors resolve against. + """ + + class RouteArgRoot(BaseState): + """Root state standing in for `rx.State`.""" + + monkeypatch.setattr("reflex.state.State", RouteArgRoot) + return RouteArgRoot + + +def test_route_arg(route_arg_root: type[BaseState]): + """`rx.route_arg` returns the var a page installed for a regular or optional arg. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + + class RouteArgSubState(route_arg_root): + """A substate, which reads the route args of its root.""" + + route_arg_root.setup_dynamic_args(get_route_args("/post/[pid]/[[lang]]")) + + for name in ("pid", "lang"): + var = rx.route_arg(name) + assert isinstance(var, StringVar) + assert var.equals(getattr(route_arg_root, name)) + assert var.equals(getattr(RouteArgSubState, name)) + + +def test_route_catch_all(route_arg_root: type[BaseState]): + """`rx.route_catch_all` returns the var a page installed for `[[...splat]]`. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + route_arg_root.setup_dynamic_args(get_route_args("/docs/[[...splat]]")) + + splat = rx.route_catch_all() + assert isinstance(splat, ArrayVar) + assert splat.equals(getattr(route_arg_root, "splat")) # noqa: B009 + + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_arg("splat") + assert str(err.value) == ( + "`splat` is installed as the catch-all `[[...splat]]`; use " + "`rx.route_catch_all()` for it." + ) + + +def test_route_catch_all_of_a_regular_arg(route_arg_root: type[BaseState]): + """A regular arg named `splat` is no catch-all. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + route_arg_root.setup_dynamic_args(get_route_args("/post/[splat]")) + + assert rx.route_arg("splat").equals(getattr(route_arg_root, "splat")) # noqa: B009 + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_catch_all() + assert str(err.value) == ( + "`splat` is installed as the regular dynamic route arg `[splat]`; use " + '`rx.route_arg("splat")` for it.' + ) + + +def test_route_arg_not_installed(route_arg_root: type[BaseState]): + """The accessors raise for an arg no page added so far has. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_arg("pid") + assert str(err.value) == ( + "No dynamic route arg `pid` is installed: no page added so far has " + "`[pid]` in its route." + ) + with pytest.raises(DynamicRouteArgNotFoundError) as err: + rx.route_catch_all() + assert str(err.value) == ( + "No catch-all route arg is installed: no page added so far has " + "`[[...splat]]` in its route." + ) + + +def test_route_accessor_names_are_not_reserved(route_arg_root: type[BaseState]): + """A state var, event handler or route arg can be named like the accessors. + + Args: + route_arg_root: The root state the accessors resolve against. + """ + + class RouteAccessorNamesState(BaseState): + """A state declaring the names of the accessors.""" + + route_arg: str = "" + + def route_catch_all(self): + """An event handler named like `rx.route_catch_all`.""" + + assert "route_arg" in RouteAccessorNamesState.get_fields() + assert "route_catch_all" in RouteAccessorNamesState.event_handlers + + route_arg_root.setup_dynamic_args(get_route_args("/x/[route_arg]")) + assert rx.route_arg("route_arg").equals(getattr(route_arg_root, "route_arg")) # noqa: B009 + + def test_router_var_dep_legacy_string() -> None: """An explicit deps=["router"] still fires when any router var changes.