Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mde-pach committed Feb 21, 2024
1 parent 19bb76a commit 1def9f3
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 35 deletions.
14 changes: 12 additions & 2 deletions blitz/ui/components/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import Any, Generic, Self, TypeVar, Protocol
from typing import Any, Generic, Self, TypeVar, Protocol, cast
from blitz.ui.blitz_ui import BlitzUI, get_blitz_ui
from typing import overload
from nicegui import ui


class NiceGUIComponent(Protocol):
Expand All @@ -15,9 +17,10 @@ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:

# Get the blitz_ui through a metaclass
class BaseComponentMeta(type):
def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> type:
def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], *, reactive: bool = False) -> type:
blitz_ui = get_blitz_ui()
namespace["blitz_ui"] = blitz_ui
namespace["reactive"] = reactive
return super().__new__(cls, name, bases, namespace)


Expand All @@ -27,6 +30,7 @@ def __init__(self, *args: Any, props: str = "", classes: str = "", **kwargs: Any
self.props: str
self.classes: str
self.blitz_ui: BlitzUI
self.reactive: bool
self.current_project = self.blitz_ui.current_project
self.current_app = self.blitz_ui.current_app

Expand All @@ -40,11 +44,17 @@ def __init__(self, *args: Any, props: str = "", classes: str = "", **kwargs: Any
self.classes = classes

self.blitz_ui = get_blitz_ui()
if self.reactive:
self.render = ui.refreshable(self.render) # type: ignore
self.render()

def render(self) -> None:
raise NotImplementedError

def refresh(self, *args: Any, **kwargs: Any) -> None:
if hasattr(self.render, "refresh"):
self.render.refresh(*args, **kwargs)

@property
def ng(self) -> V:
return self._ng
Expand Down
4 changes: 3 additions & 1 deletion blitz/ui/components/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ def __init__(self, blitz_ui: BlitzUI = get_blitz_ui()) -> None:
pass

def render(self) -> None:
FlatButton(icon="menu")
FlatButton(
icon="menu",
)


class HeaderComponent:
Expand Down
34 changes: 17 additions & 17 deletions blitz/ui/components/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,28 @@
from blitz.ui.blitz_ui import BlitzUI, get_blitz_ui
from nicegui import ui
from blitz.api.logs import InterceptHandler
from blitz.ui.components.base import BaseComponent


class LogElementHandler(InterceptHandler):
"""A logging handler that emits messages to a log element."""
class LogComponent(BaseComponent[ui.log]):
class LogHandler(InterceptHandler):
"""A logging handler that emits messages to a log element."""

def __init__(self, element: ui.log, level: int = logging.NOTSET) -> None:
self.element = element
super().__init__(level)
def __init__(self, log: ui.log, level: int = logging.NOTSET) -> None:
self.log = log
super().__init__(level)

def emit(self, record: logging.LogRecord) -> None:
try:
if record.name != "uvicorn.access.ui":
self.element.push(record.getMessage())
except Exception:
self.handleError(record)
def emit(self, record: logging.LogRecord) -> None:
try:
if record.name != "uvicorn.access.ui":
self.log.push(record.getMessage())
except Exception:
self.handleError(record)


class LogComponent:
def __init__(self, blitz_ui: BlitzUI = get_blitz_ui()) -> None:
self.blitz_ui = blitz_ui
def __init__(self) -> None:
self._logger = logging.getLogger("uvicorn.access")
super().__init__()

def render(self) -> None:
log = ui.log(max_lines=None).classes("w-full h-64 text-sm")
self._logger.addHandler(LogElementHandler(log))
self.ng = ui.log(max_lines=None).classes("w-full h-64 text-sm")
self._logger.addHandler(self.LogHandler(self.ng))
26 changes: 14 additions & 12 deletions blitz/ui/components/status.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
from typing import Any
from nicegui import ui

from blitz.ui.blitz_ui import BlitzUI, get_blitz_ui
from httpx import AsyncClient

from blitz.ui.components.base import BaseComponent

class StatusComponent:
def __init__(self, blitz_ui: BlitzUI = get_blitz_ui()) -> None:
self.blitz_ui = blitz_ui
self.app = self.blitz_ui.current_app
self.api_up = False
self.admin_up = False
ui.timer(10.0, self.set_status)

class StatusComponent(BaseComponent[ui.grid], reactive=True):
api_up: bool = False
admin_up: bool = False

def __init__(self, *args: Any, props: str = "", classes: str = "", **kwargs: Any) -> None:
ui.timer(10.0, self._set_status)
super().__init__(*args, props=props, classes=classes, **kwargs)

async def _is_api_up(self) -> bool:
async with AsyncClient() as client:
Expand All @@ -22,14 +25,12 @@ async def _is_admin_up(self) -> bool:
response = await client.get(f"{self.blitz_ui.localhost_url}/admin/")
return response.status_code == 200

async def set_status(self) -> None:
async def _set_status(self) -> None:
self.api_up = await self._is_api_up()
self.admin_up = await self._is_admin_up()
self.render.refresh()

@ui.refreshable
def render(self) -> None:
with ui.grid(rows=2, columns=2).classes("gap-4"):
def render(self) -> None: # type: ignore
with ui.grid(rows=2, columns=2).classes("gap-4") as self.ng:
ui.label("API:").classes("text-lg font-bold")
if self.api_up:
ui.icon(name="check_circle").classes("text-green-500")
Expand All @@ -40,3 +41,4 @@ def render(self) -> None:
ui.icon(name="check_circle").classes("text-green-500")
else:
ui.icon(name="error").classes("text-red-500")

1 change: 1 addition & 0 deletions blitz/ui/pages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from blitz.ui.components.header import FrameComponent


# TODO base page don't inherit
class BasePage(BaseComponent):
PAGE_NAME = "Blitz Dashboard"
FRAME: FrameComponent
Expand Down
4 changes: 2 additions & 2 deletions blitz/ui/pages/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ def render(self) -> None:
ui.table(columns=self.columns, rows=self.rows, row_key="name").classes("w-full no-shadow")
with ui.expansion("Status", value=True, icon="health_and_safety").classes("w-full text-bold text-2xl"):
# See https://github.com/zauberzeug/nicegui/issues/2174
StatusComponent().render() # type: ignore
StatusComponent()
with ui.expansion("Logs", value=False, icon="list").classes("w-full text-bold text-2xl"):
LogComponent().render()
LogComponent()
2 changes: 1 addition & 1 deletion blitz/ui/pages/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ class LogPage(BasePage):
PAGE_NAME = "Log"

def render(self) -> None:
LogComponent().render()
LogComponent()

0 comments on commit 1def9f3

Please sign in to comment.