Browse Source

Merge branch 'main' into page_updates

# Conflicts:
#	main.py
Falko Schindler 2 years ago
parent
commit
67dc1e624c
3 changed files with 24 additions and 13 deletions
  1. 15 12
      main.py
  2. 8 0
      nicegui/elements/page.py
  3. 1 1
      nicegui/ui.py

+ 15 - 12
main.py

@@ -483,24 +483,27 @@ with example(ui.timer):
 
 lifecycle = '''### Lifecycle
 
-You can run a function or coroutine on startup as a parallel task by passing it to `ui.on_startup`.
-If NiceGUI is shut down or restarted, the tasks will be automatically canceled (for example when you make a code change).
-You can also execute cleanup code with `ui.on_shutdown`.
+You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
+
+- `ui.on_startup`: Called when NiceGUI is started 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)
+
+When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
 '''
 with example(lifecycle):
-    with ui.row() as row:
-        ui.label('count:')
-        count_label = ui.label('0')
-        count = 0
+    import asyncio
+    import time
+
+    l = ui.label()
 
-    async def counter():
-        global count
+    async def run_clock():
         while True:
-            count_label.text = str(count)
-            count += 1
+            l.text = f'unix time: {time.time():.1f}'
             await asyncio.sleep(1)
 
-    ui.on_startup(counter())
+    ui.on_startup(run_clock)
+    ui.on_connect(lambda: l.set_text('new connection'))
 
 updates = '''### UI Updates
 

+ 8 - 0
nicegui/elements/page.py

@@ -88,3 +88,11 @@ class Page(jp.QuasarPage):
     def handle_javascript_result(self, msg) -> bool:
         self.waiting_javascript_commands[msg.request_id] = msg.result
         return False
+
+
+def add_head_html(self, html: str) -> None:
+    page_stack[-1].head_html += html
+
+
+def add_body_html(self, html: str) -> None:
+    page_stack[-1].body_html += html

+ 1 - 1
nicegui/ui.py

@@ -33,7 +33,7 @@ class Ui:
     from .elements.notify import Notify as notify
     from .elements.number import Number as number
     from .elements.open import open, open_async
-    from .elements.page import Page as page
+    from .elements.page import Page as page, add_head_html, add_body_html
     from .elements.radio import Radio as radio
     from .elements.row import Row as row
     from .elements.select import Select as select