فهرست منبع

Add router data to state (#228)

Thomas Brandého 2 سال پیش
والد
کامیت
1124067c12
5فایلهای تغییر یافته به همراه21 افزوده شده و 0 حذف شده
  1. 3 0
      pynecone/.templates/web/utils/state.js
  2. 2 0
      pynecone/app.py
  3. 3 0
      pynecone/event.py
  4. 12 0
      pynecone/state.py
  5. 1 0
      tests/test_state.py

+ 3 - 0
pynecone/.templates/web/utils/state.js

@@ -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;

+ 2 - 0
pynecone/app.py

@@ -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:

+ 3 - 0
pynecone/event.py

@@ -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] = {}
 

+ 12 - 0
pynecone/state.py

@@ -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.
 

+ 1 - 0
tests/test_state.py

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