Drag.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { EVENT_DRAG, EVENT_DRAGGED, EVENT_DRAGGING, EVENT_MOUNTED, EVENT_UPDATED } from '../../constants/events';
  2. import { FADE, LOOP, SLIDE } from '../../constants/types';
  3. import { EventInterface } from '../../constructors';
  4. import { Splide } from '../../core/Splide/Splide';
  5. import { BaseComponent, Components, Options } from '../../types';
  6. import { abs, isHTMLElement, isObject, matches, min, noop, prevent, sign } from '../../utils';
  7. import { FRICTION, LOG_INTERVAL, POINTER_DOWN_EVENTS, POINTER_MOVE_EVENTS, POINTER_UP_EVENTS } from './constants';
  8. /**
  9. * The interface for the Drag component.
  10. *
  11. * @since 3.0.0
  12. */
  13. export interface DragComponent extends BaseComponent {
  14. disable( disabled: boolean ): void;
  15. isDragging(): boolean;
  16. }
  17. /**
  18. * The component for dragging the slider.
  19. *
  20. * @since 3.0.0
  21. *
  22. * @param Splide - A Splide instance.
  23. * @param Components - A collection of components.
  24. * @param options - Options.
  25. *
  26. * @return A Drag component object.
  27. */
  28. export function Drag( Splide: Splide, Components: Components, options: Options ): DragComponent {
  29. const { on, emit, bind, unbind } = EventInterface( Splide );
  30. const { Move, Scroll, Controller } = Components;
  31. const { track } = Components.Elements;
  32. const { resolve, orient } = Components.Direction;
  33. const { getPosition, exceededLimit } = Move;
  34. const listenerOptions = { passive: false, capture: true };
  35. /**
  36. * The base slider position to calculate the delta of coords.
  37. */
  38. let basePosition: number;
  39. /**
  40. * The base event object saved per specific sampling interval.
  41. */
  42. let baseEvent: TouchEvent | MouseEvent;
  43. /**
  44. * Holds the previous base event object.
  45. */
  46. let prevBaseEvent: TouchEvent | MouseEvent;
  47. /**
  48. * Keeps the last TouchEvent/MouseEvent object on pointermove.
  49. */
  50. let lastEvent: TouchEvent | MouseEvent;
  51. /**
  52. * Indicates whether the drag mode is `free` or not.
  53. */
  54. let isFree: boolean;
  55. /**
  56. * Indicates whether the user is dragging the slider or not.
  57. */
  58. let dragging: boolean;
  59. /**
  60. * Indicates whether the slider exceeds limits or not.
  61. * This must not be `undefined` for strict comparison.
  62. */
  63. let hasExceeded = false;
  64. /**
  65. * Turns into `true` when the user starts dragging the slider.
  66. */
  67. let clickPrevented: boolean;
  68. /**
  69. * Indicates whether the drag component is now disabled or not.
  70. */
  71. let disabled: boolean;
  72. /**
  73. * The target element to attach listeners.
  74. */
  75. let target: Window | HTMLElement;
  76. /**
  77. * Called when the component is mounted.
  78. */
  79. function mount(): void {
  80. bind( track, POINTER_MOVE_EVENTS, noop, listenerOptions );
  81. bind( track, POINTER_UP_EVENTS, noop, listenerOptions );
  82. bind( track, POINTER_DOWN_EVENTS, onPointerDown, listenerOptions );
  83. bind( track, 'click', onClick, { capture: true } );
  84. bind( track, 'dragstart', prevent );
  85. on( [ EVENT_MOUNTED, EVENT_UPDATED ], init );
  86. }
  87. /**
  88. * Initializes the component.
  89. */
  90. function init(): void {
  91. const { drag } = options;
  92. disable( ! drag );
  93. isFree = drag === 'free';
  94. }
  95. /**
  96. * Called when the user clicks or touches the slider.
  97. * Needs to prevent the default behaviour when the slider is busy to deny any action, such as dragging images.
  98. * Note that IE does not support MouseEvent and TouchEvent constructors.
  99. *
  100. * @param e - A TouchEvent or MouseEvent object
  101. */
  102. function onPointerDown( e: TouchEvent | MouseEvent ): void {
  103. if ( ! disabled ) {
  104. const { noDrag } = options;
  105. const isTouch = isTouchEvent( e );
  106. const isDraggable = ! noDrag || ( isHTMLElement( e.target ) && ! matches( e.target, noDrag ) );
  107. if ( isDraggable && ( isTouch || ! e.button ) ) {
  108. if ( ! Move.isBusy() ) {
  109. target = isTouch ? track : window;
  110. prevBaseEvent = null;
  111. lastEvent = null;
  112. clickPrevented = false;
  113. bind( target, POINTER_MOVE_EVENTS, onPointerMove, listenerOptions );
  114. bind( target, POINTER_UP_EVENTS, onPointerUp, listenerOptions );
  115. Move.cancel();
  116. Scroll.cancel();
  117. save( e );
  118. } else {
  119. prevent( e, true );
  120. }
  121. }
  122. }
  123. }
  124. /**
  125. * Called while the user moves the pointer on the slider.
  126. *
  127. * @param e - A TouchEvent or MouseEvent object
  128. */
  129. function onPointerMove( e: TouchEvent | MouseEvent ): void {
  130. if ( ! lastEvent ) {
  131. emit( EVENT_DRAG );
  132. }
  133. lastEvent = e;
  134. if ( e.cancelable ) {
  135. if ( dragging ) {
  136. const expired = timeOf( e ) - timeOf( baseEvent ) > LOG_INTERVAL;
  137. const exceeded = hasExceeded !== ( hasExceeded = exceededLimit() );
  138. if ( expired || exceeded ) {
  139. save( e );
  140. }
  141. Move.translate( basePosition + constrain( coordOf( e ) - coordOf( baseEvent ) ) );
  142. emit( EVENT_DRAGGING );
  143. clickPrevented = true;
  144. prevent( e );
  145. } else {
  146. const diff = abs( coordOf( e ) - coordOf( baseEvent ) );
  147. let { dragMinThreshold: thresholds } = options;
  148. thresholds = isObject( thresholds ) ? thresholds : { mouse: 0, touch: +thresholds || 10 };
  149. dragging = diff > ( isTouchEvent( e ) ? thresholds.touch : thresholds.mouse );
  150. if ( isSliderDirection() ) {
  151. prevent( e );
  152. }
  153. }
  154. }
  155. }
  156. /**
  157. * Called when the user releases pointing devices.
  158. * Be aware that the TouchEvent object provided by the `touchend` does not contain `Touch` objects,
  159. * which means the last touch position is not available.
  160. *
  161. * @param e - A TouchEvent or MouseEvent object
  162. */
  163. function onPointerUp( e: TouchEvent | MouseEvent ): void {
  164. unbind( target, POINTER_MOVE_EVENTS, onPointerMove );
  165. unbind( target, POINTER_UP_EVENTS, onPointerUp );
  166. if ( lastEvent ) {
  167. if ( dragging || ( e.cancelable && isSliderDirection() ) ) {
  168. const velocity = computeVelocity( e );
  169. const destination = computeDestination( velocity );
  170. if ( isFree ) {
  171. Controller.scroll( destination );
  172. } else if ( Splide.is( FADE ) ) {
  173. Controller.go( Splide.index + orient( sign( velocity ) ) );
  174. } else {
  175. Controller.go( Controller.toDest( destination ), true );
  176. }
  177. prevent( e );
  178. }
  179. emit( EVENT_DRAGGED );
  180. }
  181. dragging = false;
  182. }
  183. /**
  184. * Saves data at the specific moment.
  185. *
  186. * @param e A TouchEvent or MouseEvent object
  187. */
  188. function save( e: TouchEvent | MouseEvent ): void {
  189. prevBaseEvent = baseEvent;
  190. baseEvent = e;
  191. basePosition = getPosition();
  192. }
  193. /**
  194. * Called when the track element is clicked.
  195. * Disables click any elements inside it while dragging.
  196. *
  197. * @param e - A MouseEvent object.
  198. */
  199. function onClick( e: MouseEvent ): void {
  200. if ( ! disabled && clickPrevented ) {
  201. prevent( e, true );
  202. }
  203. }
  204. /**
  205. * Checks whether dragging towards the slider or scroll direction.
  206. *
  207. * @return `true` if going towards the slider direction, or otherwise `false`.
  208. */
  209. function isSliderDirection(): boolean {
  210. const diffX = abs( coordOf( lastEvent ) - coordOf( baseEvent ) );
  211. const diffY = abs( coordOf( lastEvent, true ) - coordOf( baseEvent, true ) );
  212. return diffX > diffY;
  213. }
  214. /**
  215. * Computes the drag velocity.
  216. *
  217. * @param e - A TouchEvent or MouseEvent object
  218. *
  219. * @return The drag velocity.
  220. */
  221. function computeVelocity( e: TouchEvent | MouseEvent ): number {
  222. if ( Splide.is( LOOP ) || ! hasExceeded ) {
  223. const base = baseEvent === lastEvent && prevBaseEvent || baseEvent;
  224. const diffCoord = coordOf( lastEvent ) - coordOf( base );
  225. const diffTime = timeOf( e ) - timeOf( base );
  226. const isFlick = timeOf( e ) - timeOf( lastEvent ) < LOG_INTERVAL;
  227. if ( diffTime && isFlick ) {
  228. return diffCoord / diffTime;
  229. }
  230. }
  231. return 0;
  232. }
  233. /**
  234. * Computes the destination by the velocity and the `flickPower` option.
  235. *
  236. * @param velocity - The drag velocity.
  237. *
  238. * @return The destination.
  239. */
  240. function computeDestination( velocity: number ): number {
  241. return getPosition() + sign( velocity ) * min(
  242. abs( velocity ) * ( options.flickPower || 600 ),
  243. isFree ? Infinity : Components.Layout.listSize() * ( options.flickMaxPages || 1 )
  244. );
  245. }
  246. /**
  247. * Returns the `pageX` and `pageY` coordinates provided by the event.
  248. * Be aware that IE does not support both TouchEvent and MouseEvent constructors.
  249. *
  250. * @param e - A TouchEvent or MouseEvent object.
  251. * @param orthogonal - Optional. If `true`, returns the coord of the orthogonal axis against the drag one.
  252. *
  253. * @return A pageX or pageY coordinate.
  254. */
  255. function coordOf( e: TouchEvent | MouseEvent, orthogonal?: boolean ): number {
  256. return ( isTouchEvent( e ) ? e.touches[ 0 ] : e )[ `page${ resolve( orthogonal ? 'Y' : 'X' ) }` ];
  257. }
  258. /**
  259. * Returns the time stamp in the provided event object.
  260. *
  261. * @param e - A TouchEvent or MouseEvent object.
  262. *
  263. * @return A time stamp.
  264. */
  265. function timeOf( e: TouchEvent | MouseEvent ): number {
  266. return e.timeStamp;
  267. }
  268. /**
  269. * Reduces the distance to move by the predefined friction.
  270. * This does nothing when the slider type is not `slide`, or the position is inside borders.
  271. *
  272. * @param diff - Diff to constrain.
  273. *
  274. * @return The constrained diff.
  275. */
  276. function constrain( diff: number ): number {
  277. return diff / ( hasExceeded && Splide.is( SLIDE ) ? FRICTION : 1 );
  278. }
  279. /**
  280. * Checks if the provided event is TouchEvent or MouseEvent.
  281. *
  282. * @param e - An event to check.
  283. *
  284. * @return `true` if the `e` is TouchEvent.
  285. */
  286. function isTouchEvent( e: TouchEvent | MouseEvent ): e is TouchEvent {
  287. return typeof TouchEvent !== 'undefined' && e instanceof TouchEvent;
  288. }
  289. /**
  290. * Checks if now the user is dragging the slider or not.
  291. *
  292. * @return `true` if the user is dragging the slider or otherwise `false`.
  293. */
  294. function isDragging(): boolean {
  295. return dragging;
  296. }
  297. /**
  298. * Disables the component.
  299. *
  300. * @param value - Set `true` to disable the component.
  301. */
  302. function disable( value: boolean ): void {
  303. disabled = value;
  304. }
  305. return {
  306. mount,
  307. disable,
  308. isDragging,
  309. };
  310. }