select.py 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. from typing import Any, Callable, Dict, List, Optional, Union
  2. import justpy as jp
  3. from .choice_element import ChoiceElement
  4. class Select(ChoiceElement):
  5. def __init__(self, options: Union[List, Dict], *, value: Any = None, on_change: Optional[Callable] = None):
  6. """Dropdown Selection Element
  7. :param options: a list ['value1', ...] or dictionary `{'value1':'label1', ...}` specifying the options
  8. :param value: the inital value
  9. :param on_change: callback to execute when selection changes
  10. """
  11. view = jp.QSelect(options=options, input=self.handle_change, temp=False)
  12. super().__init__(view, options, value=value, on_change=on_change)
  13. def value_to_view(self, value: Any):
  14. matches = [o for o in self.view.options if o['value'] == value]
  15. if any(matches):
  16. return matches[0]['label']
  17. else:
  18. return value
  19. def handle_change(self, msg):
  20. msg['label'] = msg['value']['label']
  21. msg['value'] = msg['value']['value']
  22. return super().handle_change(msg)