Drag.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import { CLASS_ARROW, CLASS_PAGINATION_PAGE } from '../../constants/classes';
  2. import { DEFAULTS } from '../../constants/defaults';
  3. import { EVENT_DRAG, EVENT_DRAGGED, EVENT_DRAGGING, EVENT_MOUNTED, EVENT_UPDATED } from '../../constants/events';
  4. import { SCROLL_LISTENER_OPTIONS } from '../../constants/listener-options';
  5. import { DRAGGING, IDLE, MOVING, SCROLLING } from '../../constants/states';
  6. import { FADE, LOOP, SLIDE } from '../../constants/types';
  7. import { EventInterface } from '../../constructors';
  8. import { Splide } from '../../core/Splide/Splide';
  9. import { BaseComponent, Components, Options } from '../../types';
  10. import { abs, isObject, matches, min, noop, prevent, sign, timeOf } from '../../utils';
  11. import { FRICTION, LOG_INTERVAL, POINTER_DOWN_EVENTS, POINTER_MOVE_EVENTS, POINTER_UP_EVENTS } from './constants';
  12. /**
  13. * The interface for the Drag component.
  14. *
  15. * @since 3.0.0
  16. */
  17. export interface DragComponent extends BaseComponent {
  18. disable( disabled: boolean ): void;
  19. isDragging(): boolean;
  20. }
  21. /**
  22. * The component for dragging the slider.
  23. *
  24. * @since 3.0.0
  25. *
  26. * @param Splide - A Splide instance.
  27. * @param Components - A collection of components.
  28. * @param options - Options.
  29. *
  30. * @return A Drag component object.
  31. */
  32. export function Drag( Splide: Splide, Components: Components, options: Options ): DragComponent {
  33. const { on, emit, bind, unbind } = EventInterface( Splide );
  34. const { state } = Splide;
  35. const { Move, Scroll, Controller } = Components;
  36. const { track } = Components.Elements;
  37. const { resolve, orient } = Components.Direction;
  38. const { getPosition, exceededLimit } = Move;
  39. /**
  40. * The base slider position to calculate the delta of coords.
  41. */
  42. let basePosition: number;
  43. /**
  44. * The base event object saved per specific sampling interval.
  45. */
  46. let baseEvent: TouchEvent | MouseEvent;
  47. /**
  48. * Holds the previous base event object.
  49. */
  50. let prevBaseEvent: 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 exceeded = 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, SCROLL_LISTENER_OPTIONS );
  81. bind( track, POINTER_UP_EVENTS, noop, SCROLL_LISTENER_OPTIONS );
  82. bind( track, POINTER_DOWN_EVENTS, onPointerDown, SCROLL_LISTENER_OPTIONS );
  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. * - IE does not support MouseEvent and TouchEvent constructors
  99. * - The `dragging` state always becomes `true` when the user starts dragging while the slider is moving
  100. *
  101. * @param e - A TouchEvent or MouseEvent object
  102. */
  103. function onPointerDown( e: TouchEvent | MouseEvent ): void {
  104. clickPrevented = false;
  105. if ( ! disabled ) {
  106. const isTouch = isTouchEvent( e );
  107. if ( isDraggable( e.target ) && ( isTouch || ! e.button ) ) {
  108. if ( ! Controller.isBusy() ) {
  109. target = isTouch ? track : window;
  110. dragging = state.is( [ MOVING, SCROLLING ] );
  111. prevBaseEvent = null;
  112. bind( target, POINTER_MOVE_EVENTS, onPointerMove, SCROLL_LISTENER_OPTIONS );
  113. bind( target, POINTER_UP_EVENTS, onPointerUp, SCROLL_LISTENER_OPTIONS );
  114. Move.cancel();
  115. Scroll.cancel();
  116. save( e );
  117. } else {
  118. prevent( e, true );
  119. }
  120. }
  121. }
  122. }
  123. /**
  124. * Called while the user moves the pointer on the slider.
  125. *
  126. * @param e - A TouchEvent or MouseEvent object
  127. */
  128. function onPointerMove( e: TouchEvent | MouseEvent ): void {
  129. if ( ! state.is( DRAGGING ) ) {
  130. state.set( DRAGGING );
  131. emit( EVENT_DRAG );
  132. }
  133. if ( e.cancelable ) {
  134. if ( dragging ) {
  135. Move.translate( basePosition + constrain( diffCoord( e ) ) );
  136. const expired = diffTime( e ) > LOG_INTERVAL;
  137. const hasExceeded = exceeded !== ( exceeded = exceededLimit() );
  138. if ( expired || hasExceeded ) {
  139. save( e );
  140. }
  141. clickPrevented = true;
  142. emit( EVENT_DRAGGING );
  143. prevent( e );
  144. } else if ( isSliderDirection( e ) ) {
  145. dragging = shouldStart( e );
  146. prevent( e );
  147. }
  148. }
  149. }
  150. /**
  151. * Called when the user releases pointing devices.
  152. * Needs to move the slider when:
  153. * - The user drags the slider and the distance exceeds the threshold
  154. * - The user aborted the slider moving by pointerdown and just released it without dragging the slider
  155. *
  156. * @param e - A TouchEvent or MouseEvent object
  157. */
  158. function onPointerUp( e: TouchEvent | MouseEvent ): void {
  159. if ( state.is( DRAGGING ) ) {
  160. state.set( IDLE );
  161. emit( EVENT_DRAGGED );
  162. }
  163. if ( dragging ) {
  164. move( e );
  165. prevent( e );
  166. }
  167. unbind( target, POINTER_MOVE_EVENTS, onPointerMove );
  168. unbind( target, POINTER_UP_EVENTS, onPointerUp );
  169. dragging = false;
  170. }
  171. /**
  172. * Called when the track element is clicked.
  173. * Disables click any elements inside it while dragging.
  174. *
  175. * @param e - A MouseEvent object.
  176. */
  177. function onClick( e: MouseEvent ): void {
  178. if ( ! disabled && clickPrevented ) {
  179. prevent( e, true );
  180. }
  181. }
  182. /**
  183. * Saves data at the specific moment.
  184. *
  185. * @param e - A TouchEvent or MouseEvent object.
  186. */
  187. function save( e: TouchEvent | MouseEvent ): void {
  188. prevBaseEvent = baseEvent;
  189. baseEvent = e;
  190. basePosition = getPosition();
  191. }
  192. /**
  193. * Calculates the destination by the drag velocity and moves the carousel.
  194. * If motion is reduced, restores transition speed to the initial value
  195. * because it's "essential" motion for the user to recognize what happens on the carousel.
  196. *
  197. * @param e - A TouchEvent or MouseEvent object.
  198. */
  199. function move( e: TouchEvent | MouseEvent ): void {
  200. const velocity = computeVelocity( e );
  201. const destination = computeDestination( velocity );
  202. const rewind = options.rewind && options.rewindByDrag;
  203. const reduced = Components.Media.matches( 'motion' );
  204. const { go } = Controller;
  205. if ( reduced ) {
  206. options.speed = Splide._io.speed;
  207. }
  208. if ( isFree ) {
  209. Controller.scroll( destination, 0, options.snap );
  210. } else if ( Splide.is( FADE ) ) {
  211. go( orient( sign( velocity ) ) < 0 ? ( rewind ? '<' : '-' ) : ( rewind ? '>' : '+' ) );
  212. } else if ( Splide.is( SLIDE ) && exceeded && rewind ) {
  213. go( exceededLimit( true ) ? '>' : '<' );
  214. } else {
  215. go( Controller.toDest( destination ), true );
  216. }
  217. if ( reduced ) {
  218. options.speed = 0;
  219. }
  220. }
  221. /**
  222. * Checks if the drag distance exceeds the defined threshold.
  223. *
  224. * @param e - A TouchEvent or MouseEvent object.
  225. *
  226. * @return `true` if the distance exceeds the threshold, or `false` if not.
  227. */
  228. function shouldStart( e: TouchEvent | MouseEvent ): boolean {
  229. const { dragMinThreshold: thresholds } = options;
  230. const isObj = isObject( thresholds );
  231. const mouse = isObj && thresholds.mouse || 0;
  232. const touch = ( isObj ? thresholds.touch : +thresholds ) || 10;
  233. return abs( diffCoord( e ) ) > ( isTouchEvent( e ) ? touch : mouse );
  234. }
  235. /**
  236. * Checks whether dragging towards the slider or the scroll direction.
  237. *
  238. * @return `true` if dragging towards the slider direction, or otherwise `false`.
  239. *
  240. * @param e - A TouchEvent or MouseEvent object
  241. */
  242. function isSliderDirection( e: TouchEvent | MouseEvent ): boolean {
  243. return abs( diffCoord( e ) ) > abs( diffCoord( e, true ) );
  244. }
  245. /**
  246. * Computes the drag velocity.
  247. *
  248. * @param e - A TouchEvent or MouseEvent object
  249. *
  250. * @return The drag velocity.
  251. */
  252. function computeVelocity( e: TouchEvent | MouseEvent ): number {
  253. if ( Splide.is( LOOP ) || ! exceeded ) {
  254. const time = diffTime( e );
  255. if ( time && time < LOG_INTERVAL ) {
  256. return diffCoord( e ) / time;
  257. }
  258. }
  259. return 0;
  260. }
  261. /**
  262. * Computes the destination by the velocity and the `flickPower` option.
  263. *
  264. * @param velocity - The drag velocity.
  265. *
  266. * @return The destination.
  267. */
  268. function computeDestination( velocity: number ): number {
  269. return getPosition() + sign( velocity ) * min(
  270. abs( velocity ) * ( options.flickPower || 600 ),
  271. isFree ? Infinity : Components.Layout.listSize() * ( options.flickMaxPages || 1 )
  272. );
  273. }
  274. /**
  275. * Returns the coord difference between the provided and base events.
  276. *
  277. * @param e - A TouchEvent or MouseEvent object.
  278. * @param orthogonal - Optional. If `true`, returns the coord of the orthogonal axis against the drag one.
  279. *
  280. * @return The difference of the coord.
  281. */
  282. function diffCoord( e: TouchEvent | MouseEvent, orthogonal?: boolean ): number {
  283. return coordOf( e, orthogonal ) - coordOf( getBaseEvent( e ), orthogonal );
  284. }
  285. /**
  286. * Returns the elapsed time from the base event to `e`.
  287. *
  288. * @param e - A TouchEvent or MouseEvent object.
  289. *
  290. * @return The elapsed time in milliseconds.
  291. */
  292. function diffTime( e: TouchEvent | MouseEvent ): number {
  293. return timeOf( e ) - timeOf( getBaseEvent( e ) );
  294. }
  295. /**
  296. * Returns the base event.
  297. * If the base event is same with `e`, returns previous one.
  298. *
  299. * @param e - A TouchEvent or MouseEvent object.
  300. *
  301. * @return A base event.
  302. */
  303. function getBaseEvent( e: TouchEvent | MouseEvent ): TouchEvent | MouseEvent {
  304. return baseEvent === e && prevBaseEvent || baseEvent;
  305. }
  306. /**
  307. * Returns the `pageX` and `pageY` coordinates provided by the event.
  308. * Be aware that IE does not support both TouchEvent and MouseEvent constructors.
  309. *
  310. * @param e - A TouchEvent or MouseEvent object.
  311. * @param orthogonal - Optional. If `true`, returns the coord of the orthogonal axis against the drag one.
  312. *
  313. * @return A pageX or pageY coordinate.
  314. */
  315. function coordOf( e: TouchEvent | MouseEvent, orthogonal?: boolean ): number {
  316. return ( isTouchEvent( e ) ? e.changedTouches[ 0 ] : e )[ `page${ resolve( orthogonal ? 'Y' : 'X' ) }` ];
  317. }
  318. /**
  319. * Reduces the distance to move by the predefined friction.
  320. * This does nothing when the slider type is not `slide`, or the position is inside borders.
  321. *
  322. * @param diff - Diff to constrain.
  323. *
  324. * @return The constrained diff.
  325. */
  326. function constrain( diff: number ): number {
  327. return diff / ( exceeded && Splide.is( SLIDE ) ? FRICTION : 1 );
  328. }
  329. /**
  330. * Returns `true` if the user can drag the target.
  331. *
  332. * @param target - An event target.
  333. *
  334. * @return `true` if the target is draggable.
  335. */
  336. function isDraggable( target: EventTarget ): boolean {
  337. const { noDrag } = options;
  338. return ! matches( target, `.${ CLASS_PAGINATION_PAGE }, .${ CLASS_ARROW }` )
  339. && ( ! noDrag || ! matches( target, noDrag ) );
  340. }
  341. /**
  342. * Checks if the provided event is TouchEvent or MouseEvent.
  343. *
  344. * @param e - An event to check.
  345. *
  346. * @return `true` if the `e` is TouchEvent.
  347. */
  348. function isTouchEvent( e: TouchEvent | MouseEvent ): e is TouchEvent {
  349. return typeof TouchEvent !== 'undefined' && e instanceof TouchEvent;
  350. }
  351. /**
  352. * Checks if now the user is dragging the slider or not.
  353. *
  354. * @return `true` if the user is dragging the slider or otherwise `false`.
  355. */
  356. function isDragging(): boolean {
  357. return dragging;
  358. }
  359. /**
  360. * Disables the component.
  361. *
  362. * @param value - Set `true` to disable the component.
  363. */
  364. function disable( value: boolean ): void {
  365. disabled = value;
  366. }
  367. return {
  368. mount,
  369. disable,
  370. isDragging,
  371. };
  372. }