Drag.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. const diff = coordOf( e ) - coordOf( baseEvent );
  136. if ( dragging ) {
  137. Move.translate( basePosition + constrain( diff ) );
  138. const expired = timeOf( e ) - timeOf( baseEvent ) > LOG_INTERVAL;
  139. const exceeded = hasExceeded !== ( hasExceeded = exceededLimit() );
  140. if ( expired || exceeded ) {
  141. save( e );
  142. }
  143. emit( EVENT_DRAGGING );
  144. clickPrevented = true;
  145. prevent( e );
  146. } else {
  147. let { dragMinThreshold: thresholds } = options;
  148. thresholds = isObject( thresholds ) ? thresholds : { mouse: 0, touch: +thresholds || 10 };
  149. dragging = abs( 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. } else {
  181. if ( ! isFree ) {
  182. Controller.go( Splide.index, true );
  183. }
  184. }
  185. dragging = false;
  186. }
  187. /**
  188. * Saves data at the specific moment.
  189. *
  190. * @param e A TouchEvent or MouseEvent object
  191. */
  192. function save( e: TouchEvent | MouseEvent ): void {
  193. prevBaseEvent = baseEvent;
  194. baseEvent = e;
  195. basePosition = getPosition();
  196. }
  197. /**
  198. * Called when the track element is clicked.
  199. * Disables click any elements inside it while dragging.
  200. *
  201. * @param e - A MouseEvent object.
  202. */
  203. function onClick( e: MouseEvent ): void {
  204. if ( ! disabled && clickPrevented ) {
  205. prevent( e, true );
  206. }
  207. }
  208. /**
  209. * Checks whether dragging towards the slider or scroll direction.
  210. *
  211. * @return `true` if going towards the slider direction, or otherwise `false`.
  212. */
  213. function isSliderDirection(): boolean {
  214. const diffX = abs( coordOf( lastEvent ) - coordOf( baseEvent ) );
  215. const diffY = abs( coordOf( lastEvent, true ) - coordOf( baseEvent, true ) );
  216. return diffX > diffY;
  217. }
  218. /**
  219. * Computes the drag velocity.
  220. *
  221. * @param e - A TouchEvent or MouseEvent object
  222. *
  223. * @return The drag velocity.
  224. */
  225. function computeVelocity( e: TouchEvent | MouseEvent ): number {
  226. if ( Splide.is( LOOP ) || ! hasExceeded ) {
  227. const base = baseEvent === lastEvent && prevBaseEvent || baseEvent;
  228. const diffCoord = coordOf( lastEvent ) - coordOf( base );
  229. const diffTime = timeOf( e ) - timeOf( base );
  230. const isFlick = timeOf( e ) - timeOf( lastEvent ) < LOG_INTERVAL;
  231. if ( diffTime && isFlick ) {
  232. return diffCoord / diffTime;
  233. }
  234. }
  235. return 0;
  236. }
  237. /**
  238. * Computes the destination by the velocity and the `flickPower` option.
  239. *
  240. * @param velocity - The drag velocity.
  241. *
  242. * @return The destination.
  243. */
  244. function computeDestination( velocity: number ): number {
  245. return getPosition() + sign( velocity ) * min(
  246. abs( velocity ) * ( options.flickPower || 600 ),
  247. isFree ? Infinity : Components.Layout.listSize() * ( options.flickMaxPages || 1 )
  248. );
  249. }
  250. /**
  251. * Returns the `pageX` and `pageY` coordinates provided by the event.
  252. * Be aware that IE does not support both TouchEvent and MouseEvent constructors.
  253. *
  254. * @param e - A TouchEvent or MouseEvent object.
  255. * @param orthogonal - Optional. If `true`, returns the coord of the orthogonal axis against the drag one.
  256. *
  257. * @return A pageX or pageY coordinate.
  258. */
  259. function coordOf( e: TouchEvent | MouseEvent, orthogonal?: boolean ): number {
  260. return ( isTouchEvent( e ) ? e.touches[ 0 ] : e )[ `page${ resolve( orthogonal ? 'Y' : 'X' ) }` ];
  261. }
  262. /**
  263. * Returns the time stamp in the provided event object.
  264. *
  265. * @param e - A TouchEvent or MouseEvent object.
  266. *
  267. * @return A time stamp.
  268. */
  269. function timeOf( e: TouchEvent | MouseEvent ): number {
  270. return e.timeStamp;
  271. }
  272. /**
  273. * Reduces the distance to move by the predefined friction.
  274. * This does nothing when the slider type is not `slide`, or the position is inside borders.
  275. *
  276. * @param diff - Diff to constrain.
  277. *
  278. * @return The constrained diff.
  279. */
  280. function constrain( diff: number ): number {
  281. return diff / ( hasExceeded && Splide.is( SLIDE ) ? FRICTION : 1 );
  282. }
  283. /**
  284. * Checks if the provided event is TouchEvent or MouseEvent.
  285. *
  286. * @param e - An event to check.
  287. *
  288. * @return `true` if the `e` is TouchEvent.
  289. */
  290. function isTouchEvent( e: TouchEvent | MouseEvent ): e is TouchEvent {
  291. return typeof TouchEvent !== 'undefined' && e instanceof TouchEvent;
  292. }
  293. /**
  294. * Checks if now the user is dragging the slider or not.
  295. *
  296. * @return `true` if the user is dragging the slider or otherwise `false`.
  297. */
  298. function isDragging(): boolean {
  299. return dragging;
  300. }
  301. /**
  302. * Disables the component.
  303. *
  304. * @param value - Set `true` to disable the component.
  305. */
  306. function disable( value: boolean ): void {
  307. disabled = value;
  308. }
  309. return {
  310. mount,
  311. disable,
  312. isDragging,
  313. };
  314. }