joystick.py 2.6 KB

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