added dialog classmethod

This commit is contained in:
2025-09-23 04:24:12 +02:00
parent 01d9dc9fa2
commit baaa2d4349
5 changed files with 185 additions and 2 deletions

View File

@@ -34,6 +34,47 @@ class AsyncElement(ABC, Generic[T]):
return instance._element # Return the NiceGUI element with proper typing
@classmethod
async def as_dialog(cls, element_type: Type[T] = ui.column, *args, **kwargs) -> Any:
"""Create element inside a dialog and await its result
Works like create() but wraps the element in a dialog with a card that opens automatically
and returns the dialog result when submitted.
The dialog can be submitted using dialog.submit(result) from within the build() method.
Access the dialog via self._dialog in your build() implementation.
Returns the value passed to dialog.submit() or None if dismissed.
"""
# Create the dialog
dialog = ui.dialog()
dialog.open()
# Build the element inside the dialog with a card
with dialog, ui.card():
# Separate element constructor args from build args
element_args = kwargs.pop('element_args', ())
element_kwargs = kwargs.pop('element_kwargs', {})
# Create and build the instance
instance = cls(element_type, *element_args, **element_kwargs)
# Store dialog reference for potential use in build()
instance._dialog = dialog # pyright: ignore[reportAttributeAccessIssue]
await instance.build(*args, **kwargs)
# Add a reference to the async instance on the element
instance._element._async_instance = instance # pyright: ignore[reportAttributeAccessIssue]
# Await the dialog result
result = await dialog
# Clean up the dialog after it's closed
dialog.clear()
return result
def __getattr__(self, name: str) -> Any:
"""Delegate any missing attribute access to the wrapped element"""
return getattr(self._element, name)