Controller.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import { EVENT_END_INDEX_CHANGED, EVENT_REFRESH, EVENT_RESIZED, EVENT_UPDATED } from '../../constants/events';
  2. import { MOVING, SCROLLING } from '../../constants/states';
  3. import { LOOP, SLIDE } from '../../constants/types';
  4. import { AnyFunction, BaseComponent, ComponentConstructor } from '../../types';
  5. import { apply, approximatelyEqual, between, clamp, floor, isString, isUndefined, min } from '@splidejs/utils';
  6. /**
  7. * The interface for the Controller component.
  8. *
  9. * @since 3.0.0
  10. */
  11. export interface ControllerComponent extends BaseComponent {
  12. go( control: number | string, callback?: AnyFunction ): void;
  13. jump( control: number | string ): void;
  14. scroll( destination: number, duration?: number, snap?: boolean, callback?: AnyFunction ): void;
  15. getNext( destination?: boolean ): number;
  16. getPrev( destination?: boolean ): number;
  17. getEnd(): number;
  18. setIndex( index: number ): void;
  19. getIndex( prev?: boolean ): number;
  20. toIndex( page: number ): number;
  21. toPage( index: number ): number;
  22. toDest( position: number ): number;
  23. hasFocus(): boolean;
  24. isBusy(): boolean;
  25. /** @internal */
  26. getAdjacent( prev: boolean, destination?: boolean ): number;
  27. }
  28. /**
  29. * The component for controlling the slider.
  30. *
  31. * @since 3.0.0
  32. *
  33. * @param Splide - A Splide instance.
  34. * @param Components - A collection of components.
  35. * @param options - Options.
  36. * @param event - An EventInterface instance.
  37. *
  38. * @return A Controller component object.
  39. */
  40. export const Controller: ComponentConstructor<ControllerComponent> = ( Splide, Components, options, event ) => {
  41. const { on, emit } = event;
  42. const { Move, Scroll } = Components;
  43. const { getPosition, getLimit, toPosition } = Move;
  44. const { isEnough, getLength } = Components.Slides;
  45. const { omitEnd } = options;
  46. const isLoop = Splide.is( LOOP );
  47. const isSlide = Splide.is( SLIDE );
  48. const getNext = apply( getAdjacent, false );
  49. const getPrev = apply( getAdjacent, true );
  50. /**
  51. * The current index.
  52. */
  53. let currIndex = options.start || 0;
  54. /**
  55. * The latest end index.
  56. */
  57. let endIndex: number;
  58. /**
  59. * The previous index.
  60. */
  61. let prevIndex = currIndex;
  62. /**
  63. * The latest number of slides.
  64. */
  65. let slideCount: number;
  66. /**
  67. * The latest `perMove` value.
  68. */
  69. let perMove: number;
  70. /**
  71. * The latest `perMove` value.
  72. */
  73. let perPage: number;
  74. /**
  75. * Called when the component is mounted.
  76. */
  77. function mount(): void {
  78. init();
  79. on( [ EVENT_UPDATED, EVENT_REFRESH, EVENT_END_INDEX_CHANGED ], init );
  80. on( EVENT_RESIZED, onResized );
  81. }
  82. /**
  83. * Initializes some parameters.
  84. * Needs to check the number of slides since the current index may be out of the range after refresh.
  85. * The process order must be Elements -> Controller -> Move.
  86. */
  87. function init(): void {
  88. slideCount = getLength( true );
  89. perMove = options.perMove;
  90. perPage = options.perPage;
  91. endIndex = getEnd();
  92. const end = omitEnd ? endIndex : slideCount - 1;
  93. const index = clamp( currIndex, 0, end );
  94. prevIndex = index;
  95. if ( index !== currIndex ) {
  96. currIndex = index;
  97. Move.reposition();
  98. }
  99. }
  100. /**
  101. * Called when the viewport width is changed.
  102. * The end index can change if `autoWidth` or `fixedWidth` is enabled.
  103. */
  104. function onResized(): void {
  105. if ( endIndex !== getEnd() ) {
  106. emit( EVENT_END_INDEX_CHANGED );
  107. }
  108. }
  109. /**
  110. * Moves the slider by the control pattern.
  111. *
  112. * @see `Splide#go()`
  113. *
  114. * @param control - A control pattern.
  115. * @param callback - Optional. A callback function invoked after transition ends.
  116. */
  117. function go( control: number | string, callback?: AnyFunction ): void {
  118. if ( ! isBusy() ) {
  119. const dest = parse( control );
  120. const index = loop( dest );
  121. if ( canGo( dest, index ) ) {
  122. Scroll.cancel();
  123. setIndex( index );
  124. Move.move( dest, index, prevIndex, callback );
  125. }
  126. }
  127. }
  128. /**
  129. * Checks if the carousel can move or not.
  130. * - If target and current index are same, allows going only when the carousel is not moving.
  131. * Otherwise, synced carousels will provoke the infinite loop.
  132. * - If the carousel is looping (`dest !== index`),
  133. * the carousel can be shifted or has been already shifted.
  134. *
  135. * @todo dest
  136. *
  137. * @param dest - A dest index.
  138. * @param index - An actual index.
  139. *
  140. * @return `true` if the carousel can currently move, or otherwise `false`.
  141. */
  142. function canGo( dest: number, index: number ): boolean {
  143. const forward = dest > prevIndex;
  144. return index > -1
  145. && ( index !== currIndex || ! isMoving() )
  146. && ( dest === index || Move.exceededLimit( ! forward ) || Move.canShift( forward ) );
  147. }
  148. /**
  149. * Immediately jumps to the specified index.
  150. *
  151. * @param control - An index where to jump.
  152. */
  153. function jump( control: number | string ): void {
  154. const { set } = Components.Breakpoints;
  155. const { speed } = options;
  156. set( { speed: 0 } );
  157. go( control );
  158. set( { speed } );
  159. }
  160. /**
  161. * Scrolls the slider to the specified destination with updating indices.
  162. *
  163. * @param destination - The position to scroll the slider to.
  164. * @param duration - Optional. Specifies the scroll duration.
  165. * @param snap - Optional. Whether to snap the slider to the closest slide or not.
  166. * @param callback - Optional. A callback function invoked after scroll ends.
  167. */
  168. function scroll( destination: number, duration?: number, snap?: boolean, callback?: AnyFunction ): void {
  169. Scroll.scroll( destination, duration, snap, () => {
  170. const index = loop( Move.toIndex( getPosition() ) );
  171. setIndex( omitEnd ? min( index, endIndex ) : index );
  172. callback && callback();
  173. } );
  174. }
  175. /**
  176. * Parses the control and returns a slide index.
  177. *
  178. * @param control - A control pattern to parse.
  179. *
  180. * @return A `dest` index.
  181. */
  182. function parse( control: number | string ): number {
  183. let index = currIndex;
  184. if ( isString( control ) ) {
  185. const [ , indicator, number ] = control.match( /([+\-<>]\|?)(\d+)?/ ) || [];
  186. if ( indicator === '+' || indicator === '-' ) {
  187. index = computeDestIndex( currIndex + +`${ indicator }${ +number || 1 }`, currIndex );
  188. } else if ( indicator === '>' ) {
  189. index = number ? toIndex( +number ) : getNext( true );
  190. } else if ( indicator === '<' ) {
  191. index = getPrev( true );
  192. } else if ( indicator === '>|' ) {
  193. index = endIndex;
  194. }
  195. } else {
  196. index = isLoop ? control : clamp( control, 0, endIndex );
  197. }
  198. return index;
  199. }
  200. /**
  201. * Returns an adjacent destination index.
  202. *
  203. * @internal
  204. *
  205. * @param prev - Determines whether to return a previous or next index.
  206. * @param destination - Optional. Determines whether to get a destination index or a slide one.
  207. *
  208. * @return An adjacent index if available, or otherwise `-1`.
  209. */
  210. function getAdjacent( prev: boolean, destination?: boolean ): number {
  211. const number = perMove || ( hasFocus() ? 1 : perPage );
  212. const dest = computeDestIndex( currIndex + number * ( prev ? -1 : 1 ), currIndex, ! ( perMove || hasFocus() ) );
  213. if ( dest === -1 && isSlide ) {
  214. if ( ! approximatelyEqual( getPosition(), getLimit( ! prev ), 1 ) ) {
  215. return prev ? 0 : endIndex;
  216. }
  217. }
  218. return destination ? dest : loop( dest );
  219. }
  220. /**
  221. * Converts the desired destination index to the valid one.
  222. * - If the `move` option is `true`, finds the dest index whose position is different with the current one.
  223. * - This may return clone indices if the editor is the loop mode,
  224. * or `-1` if there is no slide to go.
  225. * - There are still slides where the carousel can go if borders are between `from` and `dest`.
  226. * - If `focus` is available, needs to calculate the dest index even if there are enough number of slides.
  227. *
  228. * @param dest - The desired destination index.
  229. * @param from - A base index.
  230. * @param snapPage - Optional. Whether to snap a page or not.
  231. *
  232. * @return A converted destination index, including clones.
  233. */
  234. function computeDestIndex( dest: number, from: number, snapPage?: boolean ): number {
  235. if ( isEnough() || hasFocus() ) {
  236. const index = computeMovableDestIndex( dest );
  237. if ( index !== dest ) {
  238. from = dest;
  239. dest = index;
  240. snapPage = false;
  241. }
  242. if ( dest < 0 || dest > endIndex ) {
  243. if ( ! perMove && ( between( 0, dest, from, true ) || between( endIndex, from, dest, true ) ) ) {
  244. dest = toIndex( toPage( dest ) );
  245. } else {
  246. if ( isLoop ) {
  247. dest = snapPage
  248. ? dest < 0 ? - ( slideCount % perPage || perPage ) : slideCount
  249. : dest;
  250. } else if ( options.rewind ) {
  251. dest = dest < 0 ? endIndex : 0;
  252. } else {
  253. dest = -1;
  254. }
  255. }
  256. } else {
  257. if ( snapPage && dest !== from ) {
  258. dest = toIndex( toPage( from ) + ( dest < from ? -1 : 1 ) );
  259. }
  260. }
  261. } else {
  262. dest = -1;
  263. }
  264. return dest;
  265. }
  266. /**
  267. * Finds the dest index whose position is different with the current one for `trimSpace: 'move'`.
  268. * This can be negative or greater than `length - 1`.
  269. *
  270. * @param dest - A dest index.
  271. *
  272. * @return A dest index.
  273. */
  274. function computeMovableDestIndex( dest: number ): number {
  275. if ( isSlide && options.trimSpace === 'move' && dest !== currIndex ) {
  276. const position = getPosition();
  277. while ( position === toPosition( dest ) && between( dest, 0, Splide.length - 1, ! options.rewind ) ) {
  278. dest < currIndex ? --dest : ++dest;
  279. }
  280. }
  281. return dest;
  282. }
  283. /**
  284. * Loops the provided index only in the loop mode.
  285. *
  286. * @param index - An index to loop.
  287. *
  288. * @return A looped index.
  289. */
  290. function loop( index: number ): number {
  291. return isLoop ? ( index + slideCount ) % slideCount || 0 : index;
  292. }
  293. /**
  294. * Returns the end index where the slider can go.
  295. * For example, if the slider has 10 slides and the `perPage` option is 3,
  296. * the slider can go to the slide 8 (the index is 7).
  297. * If the `omitEnd` option is available, computes the index from the slide position.
  298. *
  299. * @return An end index.
  300. */
  301. function getEnd(): number {
  302. let end = slideCount - ( hasFocus() || ( isLoop && perMove ) ? 1 : perPage );
  303. while ( omitEnd && end-- > 0 ) {
  304. if ( toPosition( slideCount - 1 ) !== toPosition( end ) ) {
  305. end++;
  306. break;
  307. }
  308. }
  309. return clamp( end, 0, slideCount - 1 );
  310. }
  311. /**
  312. * Converts the page index to the slide index.
  313. *
  314. * @param page - A page index to convert.
  315. *
  316. * @return A slide index.
  317. */
  318. function toIndex( page: number ): number {
  319. return clamp( hasFocus() ? page : perPage * page, 0, endIndex );
  320. }
  321. /**
  322. * Converts the slide index to the page index.
  323. *
  324. * @param index - An index to convert.
  325. *
  326. * @return A page index.
  327. */
  328. function toPage( index: number ): number {
  329. return hasFocus()
  330. ? min( index, endIndex )
  331. : floor( ( index >= endIndex ? slideCount - 1 : index ) / perPage );
  332. }
  333. /**
  334. * Converts the destination position to the dest index.
  335. *
  336. * @param destination - A position to convert.
  337. *
  338. * @return A dest index.
  339. */
  340. function toDest( destination: number ): number {
  341. const closest = Move.toIndex( destination );
  342. return isSlide ? clamp( closest, 0, endIndex ) : closest;
  343. }
  344. /**
  345. * Sets a new index and retains old one.
  346. *
  347. * @param index - A new index to set.
  348. */
  349. function setIndex( index: number ): void {
  350. if ( index !== currIndex ) {
  351. prevIndex = currIndex;
  352. currIndex = index;
  353. }
  354. }
  355. /**
  356. * Returns the current/previous index.
  357. *
  358. * @param prev - Optional. Whether to return previous index or not.
  359. */
  360. function getIndex( prev?: boolean ): number {
  361. return prev ? prevIndex : currIndex;
  362. }
  363. /**
  364. * Verifies if the focus option is available or not.
  365. *
  366. * @return `true` if the slider has the focus option.
  367. */
  368. function hasFocus(): boolean {
  369. return ! isUndefined( options.focus ) || options.isNavigation;
  370. }
  371. /**
  372. * Checks if the carousel is moving now or not.
  373. *
  374. * @return `true` if the carousel is moving or scrolling, or otherwise `false`.
  375. */
  376. function isMoving(): boolean {
  377. return Splide.state.is( [ MOVING, SCROLLING ] );
  378. }
  379. /**
  380. * Checks if the slider is moving/scrolling or not.
  381. *
  382. * @return `true` if the slider can move, or otherwise `false`.
  383. */
  384. function isBusy(): boolean {
  385. return isMoving() && !! options.waitForTransition;
  386. }
  387. return {
  388. mount,
  389. go,
  390. jump,
  391. scroll,
  392. getNext,
  393. getPrev,
  394. getAdjacent,
  395. getEnd,
  396. setIndex,
  397. getIndex,
  398. toIndex,
  399. toPage,
  400. toDest,
  401. hasFocus,
  402. isBusy,
  403. };
  404. };