joystick.py 1.8 KB

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