Browse Source

refactoring

Falko Schindler 2 years ago
parent
commit
82c677e457
4 changed files with 27 additions and 22 deletions
  1. 9 14
      nicegui/client.py
  2. 9 6
      nicegui/favicon.py
  3. 2 1
      nicegui/nicegui.py
  4. 7 1
      nicegui/page.py

+ 9 - 14
nicegui/client.py

@@ -3,7 +3,7 @@ import json
 import time
 import uuid
 from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
 
 from fastapi.responses import HTMLResponse
 
@@ -13,17 +13,15 @@ from .favicon import get_favicon_url
 from .slot import Slot
 from .task_logger import create_task
 
+if TYPE_CHECKING:
+    from .page import page
+
 TEMPLATE = (Path(__file__).parent / 'templates' / 'index.html').read_text()
 
 
 class Client:
 
-    def __init__(self,
-                 path: str = '/',
-                 title: Optional[str] = None,
-                 favicon: Optional[str] = None,
-                 dark: Optional[bool] = ...,
-                 ) -> None:
+    def __init__(self, page: 'page') -> None:
         self.id = globals.next_client_id
         globals.next_client_id += 1
         globals.clients[self.id] = self
@@ -45,10 +43,7 @@ class Client:
         self.head_html = ''
         self.body_html = ''
 
-        self.path = path
-        self.title = title
-        self.favicon = favicon
-        self.dark = dark
+        self.page = page
 
     @property
     def ip(self) -> Optional[str]:
@@ -75,9 +70,9 @@ class Client:
             .replace(r'{{ body_html | safe }}', f'{self.body_html}\n{vue_html}\n{vue_styles}')
             .replace(r'{{ vue_scripts | safe }}', vue_scripts)
             .replace(r'{{ js_imports | safe }}', vue.generate_js_imports())
-            .replace(r'{{ title }}', self.title if self.title is not None else globals.title)
-            .replace(r'{{ favicon_url }}', get_favicon_url(self.path, self.favicon))
-            .replace(r'{{ dark }}', str(self.dark if self.dark is not ... else globals.dark))
+            .replace(r'{{ title }}', self.page.resolve_title())
+            .replace(r'{{ favicon_url }}', get_favicon_url(self.page))
+            .replace(r'{{ dark }}', str(self.page.resolve_dark()))
         )
 
     async def handshake(self, timeout: float = 3.0, check_interval: float = 0.1) -> None:

+ 9 - 6
nicegui/favicon.py

@@ -1,25 +1,28 @@
 from pathlib import Path
+from typing import TYPE_CHECKING
 
 from fastapi.responses import FileResponse
 
 from . import globals
 
+if TYPE_CHECKING:
+    from .page import page
+
 
 def create_favicon_routes() -> None:
     fallback = Path(__file__).parent / 'static' / 'favicon.ico'
     for path, favicon in globals.favicons.items():
         if is_remote_url(favicon):
             continue
-        globals.app.add_route(f'{path}/favicon.ico', lambda _: FileResponse(favicon or globals.favicon or fallback))
-    if '/' not in globals.favicons:
-        globals.app.add_route('/favicon.ico', lambda _: FileResponse(globals.favicon or fallback))
+        globals.app.add_route(f'{"" if path == "/" else path}/favicon.ico',
+                              lambda _, favicon=favicon or globals.favicon or fallback: FileResponse(favicon))
 
 
-def get_favicon_url(path: str, favicon: str) -> str:
-    favicon = favicon or globals.favicon
+def get_favicon_url(page: 'page') -> str:
+    favicon = page.favicon or globals.favicon
     if is_remote_url(favicon):
         return favicon
-    return f'{path[1:]}/favicon.ico' if favicon else 'static/favicon.ico'
+    return f'{page.path[1:]}/favicon.ico' if favicon else 'static/favicon.ico'
 
 
 def is_remote_url(favicon: str) -> bool:

+ 2 - 1
nicegui/nicegui.py

@@ -13,6 +13,7 @@ from . import binding, globals, vue
 from .client import Client
 from .favicon import create_favicon_routes
 from .helpers import safe_invoke
+from .page import page
 from .task_logger import create_task
 
 globals.app = app = FastAPI()
@@ -21,7 +22,7 @@ globals.sio = sio = SocketManager(app=app)._sio
 app.add_middleware(GZipMiddleware)
 app.mount("/static", StaticFiles(directory=Path(__file__).parent / 'static'), name='static')
 
-Client().__enter__()
+Client(page('/')).__enter__()
 
 
 @app.get('/')

+ 7 - 1
nicegui/page.py

@@ -38,10 +38,16 @@ class page:
 
         globals.favicons[self.path] = favicon
 
+    def resolve_title(self) -> str:
+        return self.title if self.title is not None else globals.title
+
+    def resolve_dark(self) -> Optional[bool]:
+        return str(self.dark if self.dark is not ... else globals.dark)
+
     def __call__(self, func: Callable) -> Callable:
         async def decorated(*dec_args, **dec_kwargs) -> Response:
             try:
-                with Client(path=self.path, title=self.title, favicon=self.favicon, dark=self.dark) as client:
+                with Client(self) as client:
                     if any(p.name == 'client' for p in inspect.signature(func).parameters.values()):
                         dec_kwargs['client'] = client
                     result = func(*dec_args, **dec_kwargs)