Wheel.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { SCROLL_LISTENER_OPTIONS } from '../../constants/listener-options';
  2. import { MOVING } from '../../constants/states';
  3. import { Splide } from '../../core/Splide/Splide';
  4. import { BaseComponent, Components, Options } from '../../types';
  5. import { abs, prevent, timeOf } from '../../utils';
  6. import { EventInterface } from '@splidejs/utils';
  7. /**
  8. * The interface for the Wheel component.
  9. *
  10. * @since 3.0.0
  11. */
  12. export interface WheelComponent extends BaseComponent {
  13. }
  14. /**
  15. * The component for observing the mouse wheel and moving the slider.
  16. *
  17. * @since 3.0.0
  18. *
  19. * @param Splide - A Splide instance.
  20. * @param Components - A collection of components.
  21. * @param options - Options.
  22. * @param event - An EventInterface instance.
  23. *
  24. * @return A Wheel component object.
  25. */
  26. export function Wheel(
  27. Splide: Splide,
  28. Components: Components,
  29. options: Options,
  30. event: EventInterface
  31. ): WheelComponent {
  32. /**
  33. * Holds the last time when the wheel moves the slider.
  34. */
  35. let lastTime = 0;
  36. /**
  37. * Called when the component is mounted.
  38. */
  39. function mount(): void {
  40. if ( options.wheel ) {
  41. event.bind( Components.Elements.track, 'wheel', onWheel, SCROLL_LISTENER_OPTIONS );
  42. }
  43. }
  44. /**
  45. * Called when the user rotates the mouse wheel on the slider.
  46. *
  47. * @param e - A WheelEvent object.
  48. */
  49. function onWheel( e: WheelEvent ): void {
  50. if ( e.cancelable ) {
  51. const { deltaY } = e;
  52. const backwards = deltaY < 0;
  53. const timeStamp = timeOf( e );
  54. const min = options.wheelMinThreshold || 0;
  55. const sleep = options.wheelSleep || 0;
  56. if ( abs( deltaY ) > min && timeStamp - lastTime > sleep ) {
  57. Splide.go( backwards ? '<' : '>' );
  58. lastTime = timeStamp;
  59. }
  60. shouldPrevent( backwards ) && prevent( e );
  61. }
  62. }
  63. /**
  64. * Checks whether the component should prevent the default action of the wheel event or not.
  65. *
  66. * @param backwards - Set this to `true` for backwards direction.
  67. *
  68. * @return `true` if the action should be prevented.
  69. */
  70. function shouldPrevent( backwards: boolean ): boolean {
  71. return ! options.releaseWheel
  72. || Splide.state.is( MOVING )
  73. || Components.Controller.getAdjacent( backwards ) !== -1;
  74. }
  75. return {
  76. mount,
  77. };
  78. }