Browse Source

update button element, improve BindTextMixin

Falko Schindler 2 years ago
parent
commit
470ebca92f

+ 15 - 1
nicegui/binding.py

@@ -8,6 +8,7 @@ from justpy.htmlcomponents import HTMLBaseComponent
 
 from . import globals
 from .task_logger import create_task
+from .updatable import Updatable
 
 bindings = defaultdict(list)
 bindable_properties = dict()
@@ -103,7 +104,7 @@ class BindableProperty:
             self.on_change(owner, value)
 
 
-class BindMixin:
+class BindMixin(Updatable):
     """
     Mixin providing bind methods for target object attributes.
     """
@@ -126,6 +127,7 @@ class BindTextMixin(BindMixin):
     """
     Mixin providing bind methods for attribute text.
     """
+    text = BindableProperty()
 
     def bind_text_to(self, target_object, target_name, forward=lambda x: x):
         return super()._bind_to(attr='text', target_object=target_object, target_name=target_name, forward=forward)
@@ -138,6 +140,18 @@ class BindTextMixin(BindMixin):
         self.bind_text_to(target_object=target_object, target_name=target_name, forward=forward)
         return self
 
+    @property
+    def text(self) -> str:
+        return self._content
+
+    @text.setter
+    def text(self, text: str) -> None:
+        self.set_text(text)
+
+    def set_text(self, text: str) -> None:
+        self._content = text
+        self.update()
+
 
 class BindValueMixin(BindMixin):
     """

+ 8 - 7
nicegui/element.py

@@ -1,14 +1,14 @@
 import shlex
-from abc import ABC
 from typing import Callable, Dict, List, Optional
 
 from . import globals
 from .event import Event
 from .slot import Slot
 from .task_logger import create_task
+from .updatable import Updatable
 
 
-class Element(ABC):
+class Element(Updatable):
 
     def __init__(self, tag: str) -> None:
         client = globals.client_stack[-1]
@@ -19,7 +19,7 @@ class Element(ABC):
         self._style: Dict[str, str] = {}
         self._props: Dict[str, str] = {}
         self._events: List[Event] = []
-        self.content: str = ''
+        self._content: str = ''
         self.slots: Dict[str, Slot] = {}
         self.default_slot = self.add_slot('default')
 
@@ -49,7 +49,7 @@ class Element(ABC):
             'style': self._style,
             'props': self._props,
             'events': events,
-            'content': self.content,
+            'content': self._content,
             'slots': {name: [child.id for child in slot.children] for name, slot in self.slots.items()},
         }
 
@@ -114,8 +114,9 @@ class Element(ABC):
             self.update()
         return self
 
-    def on(self, type: str, handler: Callable, args: List[str] = []):
-        self._events.append(Event(element_id=self.id, type=type, args=args, handler=handler))
+    def on(self, type: str, handler: Optional[Callable], args: List[str] = []):
+        if handler:
+            self._events.append(Event(element_id=self.id, type=type, args=args, handler=handler))
         return self
 
     def handle_event(self, msg: Dict) -> None:
@@ -123,7 +124,7 @@ class Element(ABC):
             if event.type == msg['type']:
                 event.handler(msg)
 
-    def update(self) -> str:
+    def update(self) -> None:
         if not globals.loop:
             return
         ids: List[int] = []

+ 18 - 0
nicegui/elements/button.py

@@ -0,0 +1,18 @@
+from typing import Callable, Optional
+
+from ..binding import BindTextMixin
+from ..element import Element
+
+
+class Button(Element, BindTextMixin):
+
+    def __init__(self, text: str = '', *, on_click: Optional[Callable] = None) -> None:
+        """Button
+
+        :param text: the label of the button
+        :param on_click: callback which is invoked when button is pressed
+        """
+        super().__init__('q-btn')
+        self.text = text
+        self.props('color=primary')
+        self.on('click', on_click)

+ 1 - 14
nicegui/elements/label.py

@@ -1,9 +1,8 @@
-from ..binding import BindableProperty, BindTextMixin
+from ..binding import BindTextMixin
 from ..element import Element
 
 
 class Label(Element, BindTextMixin):
-    text = BindableProperty()
 
     def __init__(self, text: str = '') -> None:
         """Label
@@ -14,15 +13,3 @@ class Label(Element, BindTextMixin):
         """
         super().__init__('div')
         self.text = text
-
-    @property
-    def text(self) -> str:
-        return self.content
-
-    @text.setter
-    def text(self, value: str) -> None:
-        self.content = value
-        self.update()
-
-    def set_text(self, text: str) -> None:
-        self.text = text

+ 0 - 32
nicegui/elements/old/button.py

@@ -1,32 +0,0 @@
-from typing import Callable, Optional
-
-import justpy as jp
-
-from ..binding import BindableProperty, BindTextMixin
-from ..events import ClickEventArguments, handle_event
-from .group import Group
-
-
-class Button(Group, BindTextMixin):
-    text = BindableProperty()
-
-    def __init__(self, text: str = '', *, on_click: Optional[Callable] = None):
-        """Button
-
-        :param text: the label of the button
-        :param on_click: callback which is invoked when button is pressed
-        """
-
-        view = jp.QButton(label=text, color='primary', temp=False)
-        super().__init__(view)
-
-        self.text = text
-        self.bind_text_to(self.view, 'label')
-
-        def process_event(view, event) -> Optional[bool]:
-            return handle_event(on_click, ClickEventArguments(sender=self, socket=event.get('websocket')))
-
-        view.on('click', process_event)
-
-    def set_text(self, text: str):
-        self.text = text

+ 1 - 0
nicegui/ui.py

@@ -1,3 +1,4 @@
+from .elements.button import Button as button
 from .elements.column import Column as column
 from .elements.label import Label as label
 from .elements.row import Row as row

+ 8 - 0
nicegui/updatable.py

@@ -0,0 +1,8 @@
+from abc import ABC, abstractmethod
+
+
+class Updatable(ABC):
+
+    @abstractmethod
+    def update(self) -> None:
+        pass