Keyboard.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { ARROW_LEFT, ARROW_RIGHT } from '../../constants/arrows';
  2. import { EVENT_UPDATED } from '../../constants/events';
  3. import { BaseComponent, ComponentConstructor } from '../../types';
  4. import { prevent } from '../../../../../utils';
  5. /**
  6. * The interface for the Keyboard component.
  7. *
  8. * @since 3.0.0
  9. */
  10. export interface KeyboardComponent extends BaseComponent {
  11. disable(disabled: boolean): void;
  12. }
  13. /**
  14. * The keyboard event name.
  15. *
  16. * @since 3.6.0
  17. */
  18. const KEYBOARD_EVENT = 'keydown';
  19. /**
  20. * The component for controlling the slider by keyboards.
  21. *
  22. * @since 3.0.0
  23. *
  24. * @param Splide - A Splide instance.
  25. * @param Components - A collection of components.
  26. * @param options - Options.
  27. * @param event - An EventInterface instance.
  28. *
  29. * @return A Keyboard component object.
  30. */
  31. export const Keyboard: ComponentConstructor<KeyboardComponent> = (Splide, Components, options, event) => {
  32. const { destroy } = event;
  33. const { resolve } = Components.Direction;
  34. /**
  35. * Called when the component is mounted.
  36. */
  37. function mount(): void {
  38. const { keyboard } = options;
  39. destroy();
  40. keyboard && event.bind(keyboard === 'global' ? window : Splide.root, KEYBOARD_EVENT, onKeydown);
  41. event.on(EVENT_UPDATED, mount);
  42. }
  43. /**
  44. * Disables the keyboard input.
  45. *
  46. * @param value - Toggles disabling/enabling the keyboard input.
  47. */
  48. function disable(value: boolean): void {
  49. value ? destroy() : mount();
  50. }
  51. /**
  52. * Called when any key is pressed on the target.
  53. *
  54. * @param e - A KeyboardEvent object.
  55. */
  56. function onKeydown(e: KeyboardEvent): void {
  57. if (e.key === resolve(ARROW_LEFT)) {
  58. Splide.go('<');
  59. prevent(e, true);
  60. } else if (e.key === resolve(ARROW_RIGHT)) {
  61. Splide.go('>');
  62. prevent(e, true);
  63. }
  64. }
  65. return {
  66. mount,
  67. destroy,
  68. disable,
  69. };
  70. };