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
19 changes: 17 additions & 2 deletions docs/pages/dynamic_routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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.
```
Expand Down
1 change: 1 addition & 0 deletions news/+typed-route-arg.feature.md
Original file line number Diff line number Diff line change
@@ -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]`.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+typed-route-arg.feature.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion packages/reflex-base/src/reflex_base/constants/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__"
Expand Down
4 changes: 4 additions & 0 deletions packages/reflex-base/src/reflex_base/utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
2 changes: 1 addition & 1 deletion pyi_hashes.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
2 changes: 2 additions & 0 deletions reflex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@
"ComponentState",
"State",
"dynamic",
"route_arg",
"route_catch_all",
],
"istate.shared": ["SharedState"],
"istate.wrappers": ["get_state"],
Expand Down
2 changes: 1 addition & 1 deletion reflex/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
99 changes: 94 additions & 5 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
from reflex_base.registry import RegistrationContext
from reflex_base.utils.exceptions import (
DynamicComponentInvalidSignatureError,
DynamicRouteArgNotFoundError,
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
DynamicRouteArgShadowsStateVarError,
ReflexRuntimeError,
SetUndefinedStateVarError,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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"

Expand Down
12 changes: 12 additions & 0 deletions tests/type_checking/state.py
Original file line number Diff line number Diff line change
@@ -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]])
122 changes: 122 additions & 0 deletions tests/units/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This fixture restores only reflex.state.State, but each test registers RouteArgRoot (and the first test registers RouteArgSubState) in shared state registries that survive fixture teardown. Later tests therefore see stale route-test classes, making the suite order-dependent; isolate these tests with a registration context and restore the shared state registries and related caches in teardown.

(Based on your team's feedback about restoring shared State registries.) .

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/units/test_state.py, line 4478:

<comment>This fixture restores only `reflex.state.State`, but each test registers `RouteArgRoot` (and the first test registers `RouteArgSubState`) in shared state registries that survive fixture teardown. Later tests therefore see stale route-test classes, making the suite order-dependent; isolate these tests with a registration context and restore the shared state registries and related caches in teardown.

(Based on your team's feedback about restoring shared State registries.) .</comment>

<file context>
@@ -4455,6 +4458,125 @@ def test_router_field_names_are_reserved(name):
+    class RouteArgRoot(BaseState):
+        """Root state standing in for `rx.State`."""
+
+    monkeypatch.setattr("reflex.state.State", RouteArgRoot)
+    return RouteArgRoot
+
</file context>

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.

Expand Down
Loading