Add router data to state (#228)
This commit is contained in:
parent
6e564e6923
commit
1124067c12
@ -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;
|
||||
|
@ -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:
|
||||
|
@ -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] = {}
|
||||
|
||||
|
@ -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.
|
||||
|
||||
|
@ -153,6 +153,7 @@ def test_base_class_vars(test_state):
|
||||
"substates",
|
||||
"dirty_vars",
|
||||
"dirty_substates",
|
||||
"router_data",
|
||||
):
|
||||
continue
|
||||
prop = getattr(cls, field)
|
||||
|
Loading…
Reference in New Issue
Block a user