joystick.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from typing import Any, Callable, Optional
  2. from .custom_view import CustomView
  3. from .element import Element
  4. CustomView.use(__file__, ['nipplejs.min.js'])
  5. class JoystickView(CustomView):
  6. def __init__(self,
  7. on_start: Optional[Callable],
  8. on_move: Optional[Callable],
  9. on_end: Optional[Callable],
  10. **options: Any):
  11. super().__init__('joystick', **options)
  12. self.on_start = on_start
  13. self.on_move = on_move
  14. self.on_end = on_end
  15. self.allowed_events = ['onStart', 'onMove', 'onEnd']
  16. self.initialize(temp=False,
  17. onStart=self.handle_start,
  18. onMove=self.handle_move,
  19. onEnd=self.handle_end)
  20. def handle_start(self, msg):
  21. if self.on_start is not None:
  22. return self.on_start(msg) or False
  23. return False
  24. def handle_move(self, msg):
  25. if self.on_move is not None:
  26. return self.on_move(msg) or False
  27. return False
  28. def handle_end(self, msg):
  29. if self.on_end is not None:
  30. return self.on_end(msg) or False
  31. return False
  32. class Joystick(Element):
  33. def __init__(self, *,
  34. on_start: Optional[Callable] = None,
  35. on_move: Optional[Callable] = None,
  36. on_end: Optional[Callable] = None,
  37. **options: Any):
  38. """Joystick
  39. Create a joystick based on `nipple.js <https://yoannmoi.net/nipplejs/>`_.
  40. :param on_start: callback for when the user touches the joystick
  41. :param on_move: callback for when the user moves the joystick
  42. :param on_end: callback for when the user releases the joystick
  43. :param options: arguments like `color` which should be passed to the `underlying nipple.js library <https://github.com/yoannmoinet/nipplejs#options>`_
  44. """
  45. super().__init__(JoystickView(on_start, on_move, on_end, **options))