Browse Source

Merge pull request #782 from zauberzeug/refreshable

introduce ui.refreshable
Rodja Trappe 2 years ago
parent
commit
c558d1e29d

+ 26 - 0
nicegui/functions/refreshable.py

@@ -0,0 +1,26 @@
+from typing import Callable, List
+
+from ..element import Element
+
+
+class refreshable:
+
+    def __init__(self, func: Callable) -> None:
+        """Refreshable UI functions
+
+        The `@refreshable` decorator allows you to create functions that have a `refresh` method.
+        This method will automatically delete all elements created by the function and recreate them.
+        """
+        self.func = func
+        self.containers: List[Element] = []
+
+    def __call__(self, *args, **kwargs) -> None:
+        with Element('div') as container:
+            self.func(*args, **kwargs)
+        self.containers.append(container)
+
+    def refresh(self) -> None:
+        for container in self.containers:
+            container.clear()
+            with container:
+                self.func()

+ 1 - 0
nicegui/ui.py

@@ -66,6 +66,7 @@ from .functions.html import add_body_html, add_head_html
 from .functions.javascript import run_javascript
 from .functions.notify import notify
 from .functions.open import open
+from .functions.refreshable import refreshable
 from .functions.timer import Timer as timer
 from .functions.update import update
 from .page import page

+ 29 - 0
tests/test_refreshable.py

@@ -0,0 +1,29 @@
+from nicegui import ui
+
+from .screen import Screen
+
+
+def test_refreshable(screen: Screen) -> None:
+    numbers = []
+
+    @ui.refreshable
+    def number_ui() -> None:
+        ui.label('[' + ', '.join(str(n) for n in sorted(numbers)) + ']')
+
+    number_ui()
+    ui.button('Refresh', on_click=number_ui.refresh)
+
+    screen.open('/')
+    screen.should_contain('[]')
+
+    numbers.append(1)
+    screen.click('Refresh')
+    screen.should_contain('[1]')
+
+    numbers.append(2)
+    screen.click('Refresh')
+    screen.should_contain('[1, 2]')
+
+    numbers.clear()
+    screen.click('Refresh')
+    screen.should_contain('[]')

+ 2 - 0
website/documentation.py

@@ -306,6 +306,8 @@ def create_full() -> None:
             ui.button('Add', on_click=add)
             ui.button('Clear', on_click=clear)
 
+    load_demo(ui.refreshable)
+
     @text_demo('Async event handlers', '''
         Most elements also support asynchronous event handlers.
 

+ 18 - 0
website/more_documentation/refreshable_documentation.py

@@ -0,0 +1,18 @@
+from nicegui import ui
+
+
+def main_demo() -> None:
+    import random
+
+    numbers = []
+
+    @ui.refreshable
+    def number_ui() -> None:
+        ui.label(', '.join(str(n) for n in sorted(numbers)))
+
+    def add_number() -> None:
+        numbers.append(random.randint(0, 100))
+        number_ui.refresh()
+
+    number_ui()
+    ui.button('Add random number', on_click=add_number)