horizontal.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * The resolver component for horizontal move.
  3. *
  4. * @author Naotoshi Fujita
  5. * @copyright Naotoshi Fujita. All rights reserved.
  6. */
  7. import { applyStyle } from '../../../utils/dom';
  8. import { between } from '../../../utils/utils';
  9. /**
  10. * The resolver component for horizontal move.
  11. *
  12. * @param {Splide} Splide - A Splide instance.
  13. * @param {Object} Components - An object containing components.
  14. *
  15. * @return {Object} - The resolver object.
  16. */
  17. export default ( Splide, Components ) => {
  18. /**
  19. * Hold the Layout object.
  20. *
  21. * @type {Object}
  22. */
  23. const Layout = Components.Layout;
  24. return {
  25. /**
  26. * Set position with CSS transform.
  27. *
  28. * @param {Element} list - A list element.
  29. * @param {number} position - A new position value.
  30. */
  31. translate( list, position ) {
  32. applyStyle( list, { transform: `translateX(${ position }px)` } );
  33. },
  34. /**
  35. * Calculate position by index.
  36. *
  37. * @param {number} index - Slide index.
  38. *
  39. * @return {Object} - Calculated position.
  40. */
  41. toPosition( index ) {
  42. return this.sign * ( index * ( Layout.slideWidth + Layout.gap ) + this.offset )
  43. },
  44. /**
  45. * Calculate the closest slide index from the given position.
  46. *
  47. * @return {number} - The closest slide position.
  48. */
  49. toIndex( position ) {
  50. return Math.round( ( this.sign * position - this.offset ) / ( Layout.slideWidth + Layout.gap ) );
  51. },
  52. /**
  53. * Trim redundant spaces on the left or right edge if necessary.
  54. *
  55. * @param {number} position - Position value to be trimmed.
  56. *
  57. * @return {number} - Trimmed position.
  58. */
  59. trim( position ) {
  60. const edge = this.sign * ( Layout.listWidth - ( Layout.width + Layout.gap ) );
  61. return between( position, edge, 0 );
  62. },
  63. /**
  64. * Return sign according to the direction.
  65. *
  66. * @return {number} - -1 for LTR or 1 or RTL.
  67. */
  68. get sign() {
  69. return Components.Controller.isRtl() ? 1 : -1;
  70. },
  71. /**
  72. * Return current offset value, considering direction and a number of clones.
  73. *
  74. * @return {number} - Offset amount.
  75. */
  76. get offset() {
  77. const { width, slideWidth, gap } = Layout;
  78. const { focus } = Splide.options;
  79. let focusOffset;
  80. if ( focus === 'center' ) {
  81. focusOffset = ( width - slideWidth ) / 2;
  82. } else {
  83. focusOffset = ( parseInt( focus ) || 0 ) * ( slideWidth + gap );
  84. }
  85. return ( slideWidth + gap ) * Components.Clones.length / 2 - focusOffset;
  86. },
  87. };
  88. }