joystick.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from typing import Any, Callable, Dict, Optional
  2. from ..dependencies import register_component
  3. from ..element import Element
  4. from ..events import JoystickEventArguments, handle_event
  5. register_component('joystick', __file__, 'joystick.vue', ['lib/nipplejs.min.js'])
  6. class Joystick(Element):
  7. def __init__(self, *,
  8. on_start: Optional[Callable[..., Any]] = None,
  9. on_move: Optional[Callable[..., Any]] = None,
  10. on_end: Optional[Callable[..., Any]] = None,
  11. throttle: float = 0.05,
  12. ** options: Any) -> None:
  13. """Joystick
  14. Create a joystick based on `nipple.js <https://yoannmoi.net/nipplejs/>`_.
  15. :param on_start: callback for when the user touches the joystick
  16. :param on_move: callback for when the user moves the joystick
  17. :param on_end: callback for when the user releases the joystick
  18. :param throttle: throttle interval in seconds for the move event (default: 0.05)
  19. :param options: arguments like `color` which should be passed to the `underlying nipple.js library <https://github.com/yoannmoinet/nipplejs#options>`_
  20. """
  21. super().__init__('joystick')
  22. self._props['options'] = options
  23. self.active = False
  24. def handle_start() -> None:
  25. self.active = True
  26. handle_event(on_start, JoystickEventArguments(sender=self,
  27. client=self.client,
  28. action='start'))
  29. def handle_move(msg: Dict) -> None:
  30. if self.active:
  31. handle_event(on_move, JoystickEventArguments(sender=self,
  32. client=self.client,
  33. action='move',
  34. x=msg['args']['data']['vector']['x'],
  35. y=msg['args']['data']['vector']['y']))
  36. def handle_end() -> None:
  37. self.active = False
  38. handle_event(on_end, JoystickEventArguments(sender=self,
  39. client=self.client,
  40. action='end'))
  41. self.on('start', handle_start)
  42. self.on('move', handle_move, args=['data'], throttle=throttle),
  43. self.on('end', handle_end)