Bladeren bron

introduce on_page_ready callback for ui.page

Falko Schindler 2 jaren geleden
bovenliggende
commit
ea05fc6368
2 gewijzigde bestanden met toevoegingen van 17 en 0 verwijderingen
  1. 1 0
      main.py
  2. 16 0
      nicegui/elements/page.py

+ 1 - 0
main.py

@@ -489,6 +489,7 @@ You can run a function or coroutine as a parallel task by passing it to one of t
 - `ui.on_startup`: Called when NiceGUI is started or restarted.
 - `ui.on_startup`: Called when NiceGUI is started or restarted.
 - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
 - `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
 - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
 - `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
+- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
 - `ui.on_disconnect`: Called when a client disconnects from NiceGUI.
 - `ui.on_disconnect`: Called when a client disconnects from NiceGUI.
 
 
 When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
 When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.

+ 16 - 0
nicegui/elements/page.py

@@ -5,6 +5,7 @@ import uuid
 from typing import Callable, Optional
 from typing import Callable, Optional
 
 
 import justpy as jp
 import justpy as jp
+from addict import Dict
 from pygments.formatters import HtmlFormatter
 from pygments.formatters import HtmlFormatter
 from starlette.requests import Request
 from starlette.requests import Request
 
 
@@ -23,6 +24,7 @@ class Page(jp.QuasarPage):
                  classes: str = 'q-ma-md column items-start',
                  classes: str = 'q-ma-md column items-start',
                  css: str = HtmlFormatter().get_style_defs('.codehilite'),
                  css: str = HtmlFormatter().get_style_defs('.codehilite'),
                  on_connect: Optional[Callable] = None,
                  on_connect: Optional[Callable] = None,
+                 on_page_ready: Optional[Callable] = None,
                  on_disconnect: Optional[Callable] = None,
                  on_disconnect: Optional[Callable] = None,
                  ):
                  ):
         """Page
         """Page
@@ -47,10 +49,12 @@ class Page(jp.QuasarPage):
         self.tailwind = True  # use Tailwind classes instead of Quasars
         self.tailwind = True  # use Tailwind classes instead of Quasars
         self.css = css
         self.css = css
         self.connect_handler = on_connect
         self.connect_handler = on_connect
+        self.page_ready_handler = on_page_ready
         self.disconnect_handler = on_disconnect
         self.disconnect_handler = on_disconnect
 
 
         self.waiting_javascript_commands: dict[str, str] = {}
         self.waiting_javascript_commands: dict[str, str] = {}
         self.on('result_ready', self.handle_javascript_result)
         self.on('result_ready', self.handle_javascript_result)
+        self.on('page_ready', self.handle_page_ready)
 
 
         self.view = jp.Div(a=self, classes=classes, style='row-gap: 1em', temp=False)
         self.view = jp.Div(a=self, classes=classes, style='row-gap: 1em', temp=False)
         self.view.add_page(self)
         self.view.add_page(self)
@@ -70,6 +74,18 @@ class Page(jp.QuasarPage):
                 raise ValueError(f'invalid number of arguments (0 or 1 allowed, got {arg_count})')
                 raise ValueError(f'invalid number of arguments (0 or 1 allowed, got {arg_count})')
         return self
         return self
 
 
+    async def handle_page_ready(self, msg: Dict) -> bool:
+        if self.page_ready_handler:
+            arg_count = len(inspect.signature(self.page_ready_handler).parameters)
+            is_coro = is_coroutine(self.page_ready_handler)
+            if arg_count == 1:
+                await self.page_ready_handler(msg.socket) if is_coro else self.page_ready_handler(msg.socket)
+            elif arg_count == 0:
+                await self.page_ready_handler() if is_coro else self.page_ready_handler()
+            else:
+                raise ValueError(f'invalid number of arguments (0 or 1 allowed, got {arg_count})')
+        return False
+
     async def on_disconnect(self, websocket=None) -> None:
     async def on_disconnect(self, websocket=None) -> None:
         for disconnect_handler in ([self.disconnect_handler] if self.disconnect_handler else []) + disconnect_handlers:
         for disconnect_handler in ([self.disconnect_handler] if self.disconnect_handler else []) + disconnect_handlers:
             await disconnect_handler() if is_coroutine(disconnect_handler) else disconnect_handler()
             await disconnect_handler() if is_coroutine(disconnect_handler) else disconnect_handler()