Skip to content

Commit

Permalink
Made single-page multi-user rdy
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Ikemann committed Apr 3, 2024
1 parent a70cc38 commit 01c3ce8
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions nicegui/single_page.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import asyncio
import inspect
from typing import Callable, Dict, Union

from fastapi.routing import APIRoute

from nicegui import background_tasks, helpers, ui, core, Client
from nicegui import background_tasks, helpers, ui, core, Client, app
from nicegui.app import AppConfig


Expand All @@ -19,16 +20,17 @@ def __init__(self, path: str, **kwargs) -> None:
super().__init__()

self.routes: Dict[str, Callable] = {}
self.content: Union[ui.element, None] = None
# async access lock
self.base_path = path
self.find_api_routes()

print("Configuring SinglePageRouter with path:", path)

@ui.page(path, **kwargs)
@ui.page(f'{path}' + '{_:path}', **kwargs) # all other pages
def root_page():
self.frame()
async def root_page(client: Client):
await client.connected()
if app.storage.session.get('__pageContent', None) is None:
content: Union[ui.element, None] = RouterFrame(self.base_path).on('open', lambda e: self.open(e.args))
app.storage.session['__pageContent'] = content

def find_api_routes(self):
page_routes = set()
Expand All @@ -39,7 +41,7 @@ def find_api_routes(self):
Client.single_page_routes[route] = self
self.routes[route] = key

for route in core.app.routes:
for route in core.app.routes.copy():
if isinstance(route, APIRoute):
if route.path in page_routes:
core.app.routes.remove(route)
Expand Down Expand Up @@ -68,18 +70,13 @@ def open(self, target: Union[Callable, str], server_side=False) -> None:
if server_side:
ui.run_javascript(f'window.history.pushState({{page: "{target}"}}, "", "{target}");')

if self.content is None:
return

async def build() -> None:
with self.content:
async def build(content_element) -> None:
with content_element:
result = builder()
if helpers.is_coroutine_function(builder):
await result

self.content.clear()
background_tasks.create(build())
content = app.storage.session['__pageContent']
content.clear()

def frame(self) -> ui.element:
self.content = RouterFrame(self.base_path).on('open', lambda e: self.open(e.args))
return self.content
background_tasks.create(build(content))

0 comments on commit 01c3ce8

Please sign in to comment.