46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Self, Any, Optional
|
|
from nicegui import ui
|
|
|
|
|
|
class AsyncElement(ui.element, ABC):
|
|
"""Base class for UI elements with async initialization"""
|
|
dialog: ui.dialog | None
|
|
|
|
def __init__(self, tag: str = 'div', dialog: Optional[ui.dialog] = None) -> None:
|
|
super().__init__(tag)
|
|
self.dialog = dialog
|
|
|
|
@abstractmethod
|
|
async def build(self, *args, **kwargs) -> None:
|
|
"""Build/setup the element - must be implemented by subclasses"""
|
|
pass
|
|
|
|
@classmethod
|
|
async def create(cls, *args, **kwargs) -> Self:
|
|
"""Factory method to create and build an element instance"""
|
|
instance = cls()
|
|
await instance.build(*args, **kwargs)
|
|
return instance
|
|
|
|
@classmethod
|
|
async def as_dialog(cls, dialog_classes: str = '', card_classes: str = '', *args, **kwargs) -> Any:
|
|
"""Create as dialog and return the awaited result"""
|
|
with ui.dialog().classes(dialog_classes) as dialog:
|
|
with ui.card().classes(card_classes):
|
|
instance = cls(dialog=dialog)
|
|
await instance.build(*args, **kwargs)
|
|
|
|
result = await dialog
|
|
dialog.clear()
|
|
return result
|
|
|
|
def submit(self, result: Any) -> None:
|
|
if self.dialog:
|
|
self.dialog.submit(result)
|
|
|
|
def close_dialog(self) -> None:
|
|
"""Close the dialog with a result"""
|
|
if self.dialog:
|
|
self.dialog.close()
|