select.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from dataclasses import dataclass
  2. from typing import Any, Callable, Dict, List, Optional, Union
  3. import justpy as jp
  4. from .choice_element import ChoiceElement
  5. @dataclass(frozen=True, eq=True)
  6. class Wrapper:
  7. value: tuple
  8. class Select(ChoiceElement):
  9. def __init__(self, options: Union[List, Dict], *,
  10. label: Optional[str] = None, value: Any = None, on_change: Optional[Callable] = None):
  11. """Dropdown Selection
  12. :param options: a list ['value1', ...] or dictionary `{'value1':'label1', ...}` specifying the options
  13. :param value: the initial value
  14. :param on_change: callback to execute when selection changes
  15. """
  16. view = jp.QSelect(options=options, label=label, input=self.handle_change, temp=False)
  17. super().__init__(view, options, value=value, on_change=on_change)
  18. def value_to_view(self, value: Any):
  19. if isinstance(value, list):
  20. value = tuple(value)
  21. matches = [o for o in self.view.options if o['value'] == value]
  22. if any(matches):
  23. return matches[0]['label']
  24. else:
  25. return value
  26. def handle_change(self, msg: Dict):
  27. msg['label'] = msg['value']['label']
  28. msg['value'] = msg['value']['value']
  29. if isinstance(self.view.options[0]['value'], tuple) and isinstance(msg['value'], list):
  30. msg['value'] = tuple(msg['value'])
  31. return super().handle_change(msg)