Add router data to state (#228)

This commit is contained in:
Thomas Brandého 2023-01-08 22:48:09 +01:00 committed by GitHub
parent 6e564e6923
commit 1124067c12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 21 additions and 0 deletions

View File

@ -70,6 +70,9 @@ export const applyDelta = (state, delta) => {
*/
export const applyEvent = async (event, router, socket) => {
// Handle special events
event.router_data = (({ pathname, query }) => ({ pathname, query }))(router);
if (event.name == "_redirect") {
router.push(event.payload.path);
return;

View File

@ -297,6 +297,8 @@ async def process(app: App, event: Event) -> StateUpdate:
# Get the state for the session.
state = app.state_manager.get_state(event.token)
state.router_data = event.router_data
# Preprocess the event.
pre = app.preprocess(state, event)
if pre is not None:

View File

@ -18,6 +18,9 @@ class Event(Base):
# The event name.
name: str
# The routing data where event occured
router_data: Dict[str, Any] = {}
# The event payload.
payload: Dict[str, Any] = {}

View File

@ -45,6 +45,9 @@ class State(Base, ABC):
# The set of dirty substates.
dirty_substates: Set[str] = set()
# The routing path that triggered the state
router_data: Dict[str, Any] = {}
def __init__(self, *args, **kwargs):
"""Initialize the state.
@ -89,6 +92,7 @@ class State(Base, ABC):
"substates",
"dirty_vars",
"dirty_substates",
"router_data",
}
cls.base_vars = {
f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls)
@ -257,6 +261,14 @@ class State(Base, ABC):
field.required = False
field.default = default_value
def get_current_page(cls) -> str:
"""Obtain the path of current page from the router data.
Returns:
The current page.
"""
return cls.router_data["pathname"]
def __getattribute__(self, name: str) -> Any:
"""Get the state var.

View File

@ -153,6 +153,7 @@ def test_base_class_vars(test_state):
"substates",
"dirty_vars",
"dirty_substates",
"router_data",
):
continue
prop = getattr(cls, field)