All files / src/carousel slider.js

91.95% Statements 514/559
81.42% Branches 298/366
95.74% Functions 45/47
91.62% Lines 492/537

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066                                                      17x 1033x 1033x 9080x 9080x   1033x     25x     25x 25x               25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 125x 125x       125x     25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x       25x 25x 25x 25x 25x       576x 576x 576x 576x 12x   576x       791x 791x 791x 791x 791x 67x 67x 67x 67x                       25x 668x 668x 668x   668x                   668x 235610x 668x 668x 33x   668x 668x 668x       235551x 235551x 235551x       235582x 235582x 235610x 235610x                       235582x   235551x                     668x 31x 31x   637x 637x 637x   668x           209x 31x   209x 209x 209x 209x       668x 235x             92x 92x 92x 92x 19x 19x 19x 19x     73x   92x 92x 92x 92x 90x 90x   2x   92x           25x           102x 102x 15x     15x 15x 15x 15x 15x   15x 15x 10x 10x   5x 5x   87x 10x 10x 5x 5x                   25x 11x 11x 10x 10x 1x 1x           1x 1x               25x 593x 309x 309x 309x   284x 284x             25x 284x 284x 284x             25x                         25x 8092x 8092x 8092x 8092x 8092x 25x 25x 25x 25x 8067x 8013x 8013x 54x       54x         25x 167556x   167556x 117106x 117106x 114514x     50450x   167556x               25x           8200x             8200x       8200x 8200x 118x   8082x   8200x 8200x 8200x 8200x 8200x 817x 7x   810x     7383x   8200x   8200x       47x 47x       8200x 8200x       88x   88x   25x 25x 25x 25x     16x 16x     15x 15x 15x 15x     14x 14x 14x 14x   18x   88x 88x 64x     8200x 8200x 54x 42x   54x 54x 54x 54x 8146x       8200x 8200x 8200x 2x 2x   2x 4x 2x   2x 2x   8198x 8198x 8198x   8198x 110060x 7967x   8198x 8198x     8200x 817x 817x     4765x 4765x 4765x 4709x 4709x           4765x 4765x 4765x 4674x 4674x       7383x                 7383x               7383x 7383x   70814x 70814x 70814x 69982x 69982x       70814x 70814x 70814x 69201x 69201x               8200x 8198x 8198x 8198x 9813x 231x 231x 231x 200x     8198x 8198x     8200x     8200x         8200x                     25x 164964x 164964x 164964x 164964x     25x 764x         764x 764x 714x 714x 5x 709x 704x   5x 5x   714x 714x 714x   714x     714x 714x   50x           25x 96x 96x 96x 96x 96x   96x 96x 12x 12x 1x 1x               96x         25x 8200x 8200x                               25x   16x 14x       2x             25x   16x 14x       2x             167831x             25x 79x   79x 79x 52x 4x   27x 27x           79x   79x 49x   30x 30x     79x       79x 79x 79x 79x 79x                 25x 40x 14x   40x 36x   4x 4x               25x 20x 11x   20x 17x   3x 3x                 25x   25x             209x 209x 209x 209x 209x 209x 209x   8x 4x 8x     65x 29x 65x     59x 28x 59x     47x 18x 47x     24x 24x     6x   209x 209x 666x 209x 209x   457x 457x 457x 457x     209x 140x 140x           6x 6x 4x   2x               134x       140x 583x 583x 583x   216x 90x 216x     201x 62x 201x     113x 16x 113x     53x 53x             2515x 209x 1706x 1706x 1706x   209x           816x 816x 816x 816x   816x                         816x 814x       11x 11x       11x 11x       814x       13x 13x       13x 13x               816x 217x 217x                   217x 217x       16x 16x 16x 16x 16x 7x 7x 7x   9x 9x 9x   16x       16x 16x           217x     816x     816x     1607x 1607x 25x                                 816x       816x           17x 17x      
import React, { Component, Fragment } from 'react';
import throttle from 'lodash/throttle';
import each from 'lodash/each';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import classNames from 'classnames';
import ResizeObserver from 'resize-observer-polyfill';
import CircularArray from './array';
import { defaultProps, propTypes } from './types';
import { PrevArrow, NextArrow } from './arrows';
import Dots from './dots';
import {
  signupListener,
  removeListener,
  handleCarouselTap,
  handleAutoplayPause,
  handleCarouselDrag,
  handleCarouselRelease,
  handleClick,
  handleKeyDown,
  handleResize,
  handleResizeHeight,
  handleWheel,
  handleVisibilityChange,
} from './listener';
// import './style.css';
 
const extractObject = (spec, keys) => {
  const newObject = {};
  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    newObject[key] = spec[key];
  }
  return newObject;
};
class Slider extends Component {
  isMounted = true;
 
  constructor(props) {
    super(props);
    this.state = {
      SliderRef: null,
      width: 0,
      height: 0,
      autoplaying: null,
      settings: defaultProps,
      activeIndex: 0
    };
    this.touchObject = {};
    this.newChildren = [];
    this.virtualList = [];
    this.center = 0;
    this.offset = 0;
    this.target = 0;
    this.items = null;
    this.virtualItem = null;
    this.dim = 1;
    this.xform = '';
    this.resizeObserver = null;
    this.autoplayTimer = null;
    ['', 'Webkit', 'Moz', 'O', 'ms'].every((prefix) => {
      const e = `${prefix}Transform`;
      Iif (typeof document !== 'undefined' && typeof document.body.style[e] !== 'undefined') {
        this.xform = e;
        return false;
      }
      return true;
    });
    /* switch */
    this.doubleTrigger = false;
    this.initialSet = false;
    this.beforeChangeTrigger = false;
    this.scrollEnd = false;
    this.autoplayTimer = null;
    this.scrollType = {};
    this.scrollOptions = {};
    this.rerender = false;
    this.resizeHeight = false;
    this.endIndex = null;
    this.changeWindow = false;
    /* functionBind */
    this.scroll = this.scroll.bind(this);
    this.setRef = this.setRef.bind(this);
    this.slideInit = this.slideInit.bind(this);
    this.slickNext = this.slickNext.bind(this);
    this.slickPrev = this.slickPrev.bind(this);
    this.slickSet = this.slickSet.bind(this);
    this.cycleTo = this.cycleTo.bind(this);
    this.autoPlay = this.autoPlay.bind(this);
 
    this.handleCarouselTap = handleCarouselTap.bind(this);
    this.signupListener = signupListener.bind(this);
    this.removeListener = removeListener.bind(this);
    this.handleCarouselDrag = handleCarouselDrag.bind(this);
    this.handleCarouselRelease = handleCarouselRelease.bind(this);
    this.handleAutoplayPause = handleAutoplayPause.bind(this);
    this.handleResize = throttle(handleResize.bind(this), 1000, { leading: true });
    this.handleResizeHeight = throttle(handleResizeHeight.bind(this), 500);
    this.handleVisibilityChange = handleVisibilityChange.bind(this);
    this.handleKeyDown = handleKeyDown.bind(this);
    this.handleClick = handleClick.bind(this);
    this.handleWheel = handleWheel.bind(this);
  }
 
  componentDidMount() {
    this.isMounted = true;
    window.addEventListener('resize', this.handleResize);
    this.init();
    const { onInit } = this.props;
    if (onInit && typeof onInit === 'function') onInit(this);
  }
 
  shouldComponentUpdate(nextProps, nextState) {
    this.init();
    const { slidesPerRow, rows } = nextProps;
    const { settings: { slidesPerRow: originPerRow, rows: originRows } } = this.state;
    if (slidesPerRow !== originPerRow || rows !== originRows) {
      this.resizeHeight = false;
    }
    return isEqual(nextProps, this.props) || isEqual(nextState, this.state);
  }
 
  componentDidUpdate(prevProps) {
    const { SliderRef } = this.state;
    const newProps = { ...this.props, children: [] };
    const newPrevProps = { ...prevProps, children: [] };
    const { children } = this.props;
    if (!isEqual(newProps, newPrevProps) || prevProps.children.length !== children.length) {
      const { onReInit } = this.props;
      this.init();
      this.setRef(SliderRef);
      if (onReInit && typeof onReInit === 'function') onReInit(this);
    }
  }
 
  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
    this.isMounted = false;
  }
 
  /**
   * settings init
   */
  init = () => {
    let { settings, width } = this.state;
    const { activeIndex } = this.state;
    settings = { ...defaultProps, ...this.props };
    // force showing one slide and scrolling by one if the fade mode is on
    Iif (settings.fade) {
      if (
        settings.slidesToShow > 1 && process.env.NODE_ENV !== 'production'
      ) {
        console.warn(
          `slidesToShow should be equal to 1 when fade is true, you're using ${settings.slidesToShow}`
        );
      }
      settings.slidesToShow = 1;
    }
    let { children } = this.props;
    children = React.Children.toArray(children).filter((child) => (typeof child === 'string' ? !!child.trim() : !!child));
    const newWith = this.widthInit();
    if (width !== newWith) {
      width = newWith;
    }
    const newChildren = [];
    for (
      let i = 0;
      i < children.length;
      i += settings.rows * settings.slidesPerRow
    ) {
      const newSlide = [];
      for (
        let j = i;
        j < i + settings.rows * settings.slidesPerRow;
        j += settings.slidesPerRow
      ) {
        const row = [];
        for (let k = j; k < j + settings.slidesPerRow; k += 1) {
          Eif (k < children.length) {
            row.push(
              React.cloneElement(children[k], {
                key: 100 * i + 10 * j + k,
                tabIndex: -1,
                style: {
                  width: `${100 / settings.slidesPerRow}%`,
                  display: 'inline-block'
                }
              })
            );
          }
        }
        newSlide.push(<div className="carousel-row" key={10 * i + j}>{row}</div>);
      }
      newChildren.push(
        <div
          data-carouselkey={i}
          key={i}
          className="carousel-item"
          style={{ width: `${width}px`, display: 'none' }}
        >
          {newSlide}
        </div>
      );
    }
    if (this.newChildren.length !== newChildren.length) {
      this.rerender = true;
      this.newChildren = newChildren;
    } else {
      this.rerender = false;
      this.newChildren = newChildren;
      this.virtualList = newChildren;
    }
    if (
      settings.virtualList
      && this.items
      && this.items.length === this.newChildren.length
      && !this.rerender
    ) {
      if (this.endIndex === activeIndex) {
        this.endIndex = null;
      }
      this.virtualList = this.createVirtualList();
      this.forceUpdate(() => {
        Eif (!this.resizeHeight) {
          this.connectObserver();
        }
      });
    }
    if (!isEqual(get(this.state, 'settings'), settings) && this.isMounted) {
      this.setState({ settings });
    }
  };
 
  /**
   * Get slider reference
   */
  setRef = (element) => this.setState({ SliderRef: element }, () => {
    const slides = element.querySelectorAll('.carousel-item');
    const { settings: { virtualList } } = this.state;
    if (virtualList) {
      this.virtualList = this.newChildren;
      this.forceUpdate(() => {
        this.items = new CircularArray(element.querySelectorAll('.carousel-item'));
        this.virtualItem = null;
      });
    } else {
      this.items = new CircularArray(slides);
    }
    this.slideInit();
    const { settings } = this.state;
    const { slidesToShow } = settings;
    if (slidesToShow < slides.length) {
      this.signupListener();
      this.autoPlay();
    } else {
      this.removeListener();
    }
    element.addEventListener('click', this.handleClick);
  });
 
  /**
   * autoPlay func
   */
  autoPlay = () => {
    const {
      SliderRef,
      settings: {
        autoplay, autoplaySpeed, pauseOnHover
      }
    } = this.state;
    if (autoplay && autoplaySpeed > 0 && !this.autoplayTimer) {
      this.scrollType = {
        type: 'autoplay'
      };
      this.autoplayTimer = setInterval(() => {
        const { autoplayScroll } = this.props;
        const { activeIndex } = this.state;
        this.beforeChangeTrigger = false;
        this.slickNext(activeIndex + autoplayScroll);
      }, autoplaySpeed);
      window.addEventListener('visibilitychange', this.handleVisibilityChange);
      if (pauseOnHover) {
        SliderRef.addEventListener('mouseover', this.handleAutoplayPause);
        SliderRef.removeEventListener('mouseleave', this.autoPlay);
      } else {
        SliderRef.removeEventListener('mouseover', this.handleAutoplayPause);
        SliderRef.removeEventListener('mouseleave', this.autoPlay);
      }
    } else if (autoplay && autoplaySpeed && this.autoplayTimer) {
      this.autoPlayInit();
      if (!pauseOnHover) {
        SliderRef.removeEventListener('mouseover', this.handleAutoplayPause);
        SliderRef.removeEventListener('mouseleave', this.autoPlay);
      }
    }
  };
 
  /**
   * autoPlay init func
   * @param {Object} options
   * @param {Number} options.autoplaySpeed
   */
  autoPlayInit = () => {
    const { settings } = this.state;
    if (settings.autoplay) {
      this.handleAutoplayPause();
      this.autoPlay();
    } else Eif (this.isMounted) {
      this.setState({
        settings: {
          ...settings,
          autoplay: true
        }
      }, () => {
        this.handleAutoplayPause();
        this.autoPlay();
      });
    }
  };
 
  /**
   * ResizeObserver connect
   */
  connectObserver = () => {
    if (!this.resizeObserver) {
      const { SliderRef } = this.state;
      this.resizeObserver = new ResizeObserver(this.handleResizeHeight);
      this.resizeObserver.observe(SliderRef.querySelector('.carousel-item'));
    } else {
      this.disconnectObserver();
      this.connectObserver();
    }
  };
 
  /**
   * ResizeObserver disconnect
   */
  disconnectObserver = () => {
    Eif (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
  };
 
  /**
   * Tracks scrolling information
   */
  track = () => {
    const now = Date.now();
    const elapsed = now - this.timestamp;
    this.timestamp = now;
    const delta = this.offset - this.frame;
    this.frame = this.offset;
    const v = (1000 * delta) / (1 + elapsed);
    this.velocity = 0.8 * v + 0.2 * this.velocity;
  };
 
  /**
   * Auto scrolls to nearest carousel item.
   */
  autoScroll = (type) => {
    const { settings } = this.state;
    Eif (this.amplitude) {
      const elapsed = Date.now() - this.timestamp;
      const delta = this.amplitude * Math.exp(-elapsed / settings.duration);
      if (this.doubleTrigger) {
        this.beforeChangeTrigger = false;
        this.scroll('auto', this.target - delta);
        requestAnimationFrame(this.autoScroll);
        this.doubleTrigger = false;
      } else if (delta > 2 || delta < -2) {
        this.scroll(type === 'start' ? type : 'auto', this.target - delta);
        requestAnimationFrame(this.autoScroll);
      } else Iif (this.changeWindow) {
        this.changeWindow = false;
        this.scroll('auto', this.target);
      } else {
        this.scroll('end', this.target);
      }
    }
  };
 
  getItem = (scrollItem, index) => {
    const { settings: { virtualList } } = this.state;
    let el;
    if (virtualList) {
      const keyIndex = scrollItem.getKeyIndex(index);
      if (keyIndex >= 0) {
        el = scrollItem.get(keyIndex);
      }
    } else {
      el = scrollItem.get(index);
    }
    return el;
  }
 
  /**
   * Scroll to target
   * @param {string} type
   * @param {Number} x
   */
  scroll = (type, x) => {
    const {
      SliderRef,
      width,
      settings,
      activeIndex
    } = this.state;
    const {
      centerMode,
      beforeChange,
      afterChange,
      slidesToShow,
      virtualList
    } = settings;
    // Start actual scroll
    let i;
    let el;
    let alignment = 'translateX(0px)';
    if (!x) {
      this.offset = width * activeIndex * 2;
    } else {
      this.offset = typeof x === 'number' ? x : this.offset;
    }
    this.center = Math.floor((this.offset + this.dim / 2) / this.dim);
    const delta = this.offset - this.center * this.dim;
    const dir = delta < 0 ? 1 : -1;
    const tween = (-dir * delta * 2) / this.dim;
    if (centerMode) {
      if (slidesToShow % 2 === 0) {
        alignment = `translateX(${width * (slidesToShow / 2)}px)`;
      } else {
        alignment = `translateX(${(SliderRef.clientWidth - width) / 2 - settings.centerPadding}px)`;
      }
    } else {
      alignment = 'translateX(0px)';
    }
    const { type: scrollType, direction } = this.scrollType;
    // Track scrolling state
    if (
      !SliderRef.classList.contains('scrolling')
      && scrollType !== 'arrows'
      && (type !== 'init' && type !== 'resize')) {
      this.swiping = true;
      SliderRef.classList.add('scrolling');
    }
    // center
    // Don't show wrapped items.
    const index = this.wrap(this.center);
    if (
      !this.beforeChangeTrigger
      && (type !== 'start' && type !== 'end' && type !== 'init')
    ) {
      this.beforeChangeTrigger = true;
      let newIndex;
      switch (scrollType) {
        case 'arrows': {
          const slides = settings.arrowsScroll;
          this.scrollDistance = slides;
          newIndex = this.items.getIndex(direction === 'prev' ? activeIndex - slides : activeIndex + slides);
          break;
        }
        case 'dots': {
          newIndex = this.scrollOptions.index * this.scrollOptions.dotsScroll;
          break;
        }
        case 'autoplay': {
          const slides = settings.autoplayScroll;
          this.scrollDistance = slides;
          newIndex = this.items.getIndex(activeIndex + slides);
          break;
        }
        case 'wheel': {
          const slides = settings.wheelScroll;
          this.scrollDistance = slides;
          newIndex = this.items.getIndex(direction === 'prev' ? activeIndex - slides : activeIndex + slides);
          break;
        }
        default: break;
      }
      this.endIndex = newIndex;
      if (beforeChange && typeof beforeChange === 'function') {
        beforeChange(activeIndex, newIndex);
      }
    }
    if (type !== 'end' && this.scrollEnd) this.scrollEnd = false;
    if (type === 'end') {
      if (afterChange && typeof afterChange === 'function' && !this.scrollEnd) {
        afterChange(this.wrap(this.center));
      }
      this.scrollEnd = true;
      SliderRef.classList.remove('scrolling');
      this.beforeChangeTrigger = false;
      this.swiping = false;
    } else Iif (this.scrollEnd) {
      this.scrollEnd(true);
    }
 
    this.virtualItem = this.virtualItem || new CircularArray(SliderRef.querySelectorAll('.carousel-item'), this.items);
    const scrollItem = virtualList ? this.virtualItem : this.items;
    if (scrollItem.length <= slidesToShow) {
      el = this.getItem(scrollItem, 0);
      Eif (el) {
        // Add active class to center item.
        Eif (el.classList.contains('active')) {
          each(SliderRef.querySelectorAll('.carousel-item'), (ele) => ele.classList.remove('active'));
          el.classList.add('active');
        }
        const transformString = `${alignment} translateX(0px)`;
        this.updateItemStyle(el, transformString);
      }
    } else Eif (!this.noWrap || (this.center >= 0 && this.center < scrollItem.length)) {
      el = this.getItem(scrollItem, index);
      Eif (el) {
        // Add active class to center item.
        if (el.classList.contains('active')) {
          each(SliderRef.querySelectorAll('.carousel-item'), (ele) => ele.classList.remove('active'));
          el.classList.add('active');
        }
        const transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir * settings.shift * tween * i}px)`;
        this.updateItemStyle(el, transformString);
      }
    }
    if (centerMode) {
      const half = Math.floor(scrollItem.length / 2);
      for (i = 1; i <= half; i += 1) {
        // right side
        // Don't show wrapped items.
        Eif (!this.noWrap || this.center + i < scrollItem.length) {
          el = this.getItem(scrollItem, this.wrap(this.center + i));
          if (el) {
            const transformString = `${alignment} translateX(${settings.shift + (this.dim * i - delta) / 2}px)`;
            this.updateItemStyle(el, transformString);
          }
        }
 
        // left side
        // Don't show wrapped items.
        Eif (!this.noWrap || this.center - i >= 0) {
          el = this.getItem(scrollItem, this.wrap(this.center - i));
          if (el) {
            const transformString = `${alignment} translateX(${-settings.shift + (-this.dim * i - delta) / 2}px)`;
            this.updateItemStyle(el, transformString);
          }
        }
      }
    } else Iif (scrollItem.length <= slidesToShow) {
      for (i = 1; i < scrollItem.length; i += 1) {
        el = this.getItem(scrollItem, i);
        if (el) {
          const transformString = `${alignment} translateX(${settings.shift + (this.dim * i - delta) / 2}px)`;
          this.updateItemStyle(el, transformString);
        }
      }
    } else {
      for (i = 1; i < slidesToShow; i += 1) {
        el = this.getItem(scrollItem, this.wrap(this.center + i));
        if (el) {
          const transformString = `${alignment} translateX(${settings.shift + (this.dim * i - delta) / 2}px)`;
          this.updateItemStyle(el, transformString);
        }
      }
 
      const half = Math.ceil((scrollItem.length - slidesToShow) / 2);
      for (i = 0; i < half; i += 1) {
        // right side
        Eif (!this.noWrap || this.center + slidesToShow + i < scrollItem.length) {
          el = this.getItem(scrollItem, this.wrap(this.center + slidesToShow + i));
          if (el) {
            const transformString = `${alignment} translateX(${settings.shift + (this.dim * (slidesToShow + i) - delta) / 2}px)`;
            this.updateItemStyle(el, transformString);
          }
        }
        // left side
        Eif (!this.noWrap || this.center + slidesToShow + i < scrollItem.length) {
          el = this.getItem(scrollItem, this.wrap(this.center - i - 1));
          if (el) {
            const transformString = `${alignment} translateX(${-settings.shift + (-this.dim * (i + 1) - delta) / 2}px)`;
            this.updateItemStyle(el, transformString);
          }
        }
      }
    }
 
    // center
    // Don't show wrapped items.
    if ((!this.noWrap || (this.center < this.items.length)) && slidesToShow < scrollItem.length) {
      el = this.getItem(scrollItem, this.center);
      Eif (el) {
        if (!el.classList.contains('active')) {
          each(SliderRef.querySelectorAll('.carousel-item'), (ele) => ele.classList.remove('active'));
          el.classList.add('active');
          const newActiveIndex = this.wrap(this.center);
          if (this.beforeChangeTrigger && this.isMounted) {
            this.setState({ activeIndex: newActiveIndex }, () => { this.virtualItem = null; });
          }
        }
        const transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir * settings.shift * tween}px)`;
        this.updateItemStyle(el, transformString);
      }
    }
    this.adaptHeight();
 
    // onCycleTo callback
    const currItem = SliderRef.querySelectorAll('.carousel-item')[
      this.wrap(this.center)
    ];
 
    // One time callback
    Iif (typeof this.oneTimeCallback === 'function') {
      this.oneTimeCallback.call(this, currItem, this.dragged);
      this.oneTimeCallback = null;
    }
  };
 
  /**
   * Cycle to target
   * @param {Element} el
   * @param {String} transform
   */
  updateItemStyle = (el, transform) => {
    const newEl = el;
    newEl.style[this.xform] = transform;
    newEl.style.zIndex = 1;
    newEl.style.display = '';
  };
 
  widthInit = () => {
    const { settings, SliderRef } = this.state;
    const {
      centerMode,
      centerPadding,
      slidesToShow
    } = settings;
    if (SliderRef) {
      let padding = 0;
      if (typeof centerPadding === 'string') {
        [padding] = centerPadding.match(/\d+/g);
      } else if (typeof centerPadding === 'number') {
        padding = centerPadding;
      } else {
        padding = 50;
        console.warn('centerPadding have to be number or string like 50px');
      }
      let { offsetWidth } = SliderRef;
      Eif (offsetWidth <= 0) {
        offsetWidth = window.innerWidth;
      }
      const sliderWidth = centerMode
        ? offsetWidth - padding * 2
        : offsetWidth;
      const width = sliderWidth / slidesToShow;
      return width;
    }
    return 0;
  }
 
  /**
   * Carousel first initional
   */
  slideInit = () => {
    const { SliderRef, settings: { initialSlide } } = this.state;
    Eif (SliderRef && this.isMounted) {
      const width = this.widthInit();
      this.setState({ width }, () => {
        this.dim = width * 2;
        // this.settings.gutter = padding;
        this.scroll('init');
        if (initialSlide) {
          Eif (typeof initialSlide === 'number') {
            if (initialSlide > 0 && !this.initialSet) {
              this.slickSet(initialSlide);
              this.initialSet = true;
            }
          } else {
            this.slickSet(0);
            this.initialSet = false;
            console.warn('initialSlide must be a number');
          }
        }
        this.connectObserver();
      });
    }
  };
 
  adaptHeight = () => {
    const { settings, SliderRef, height } = this.state;
    Iif (settings.adaptiveHeight && SliderRef) {
      const index = this.wrap(this.center);
      const elem = this.items.get(index);
      const { offsetHeight } = elem;
      if (height !== offsetHeight && offsetHeight > 0 && this.isMounted) {
        this.setState({
          height: offsetHeight
        });
      }
    }
  };
 
  /**
   * Get x position from event
   * @param {Event} e
   */
  xpos = (e) => {
    // touch event
    if (e.targetTouches && e.targetTouches.length >= 1) {
      return e.targetTouches[0].clientX;
    }
 
    // mouse event
    return e.clientX;
  };
 
  /**
   * Get y position from event
   * @param {Event} e
   */
  ypos = (e) => {
    // touch event
    if (e.targetTouches && e.targetTouches.length >= 1) {
      return e.targetTouches[0].clientY;
    }
 
    // mouse event
    return e.clientY;
  };
 
  /**
   * Wrap index
   * @param {Number} x
   */
  wrap = (x) => this.items.getIndex(x);
 
  /**
   * Cycle to target
   * @param {Number} n
   * @param {Function} callback
   */
  cycleTo = (n, callback) => {
    let diff = (this.center % this.items.length) - n;
    // Account for wraparound.
    Eif (!this.noWrap) {
      if (diff < 0) {
        if (Math.abs(diff + this.items.length) < Math.abs(diff)) {
          diff += this.items.length;
        }
      } else Eif (diff > 0) {
        Iif (Math.abs(diff - this.items.length) < diff) {
          diff -= this.items.length;
        }
      }
    }
 
    this.target = this.dim * Math.round(this.offset / this.dim);
    // Next
    if (diff < 0) {
      this.target += this.dim * Math.abs(diff);
      // Prev
    } else Eif (diff > 0) {
      this.target -= this.dim * diff;
    }
    // Set one time callback
    Iif (typeof callback === 'function') {
      this.oneTimeCallback = callback;
    }
    // Scroll
    Eif (this.offset !== this.target) {
      this.amplitude = this.target - this.offset;
      this.timestamp = Date.now();
      requestAnimationFrame(() => {
        this.autoScroll('start');
      });
    }
  };
 
  /**
   * Cycle to next item
   * @param {Number} n
   */
  slickNext = (n) => {
    if (this.scrollType.type === 'arrows') {
      this.doubleTrigger = true;
    }
    if (typeof n === 'number') {
      this.cycleTo(n);
    } else {
      const { activeIndex } = this.state;
      this.cycleTo(activeIndex + 1);
    }
  };
 
  /**
   * Cycle to previous item
   * @param {Number} n
   */
  slickPrev = (n) => {
    if (this.scrollType.type === 'arrows') {
      this.doubleTrigger = true;
    }
    if (typeof n === 'number') {
      this.cycleTo(n);
    } else {
      const { activeIndex } = this.state;
      this.cycleTo(activeIndex - 1);
    }
  };
 
  /**
   * Cycle to nth item
   * @param {Number} [n]
   * @param {Function} callback
   */
  slickSet = (n, callback) => this.cycleTo(n, callback);
 
  createVirtualList = () => {
    const {
      settings: {
        slidesToShow,
        overScan
      },
      activeIndex
    } = this.state;
    Eif (this.virtualList.length > (((slidesToShow + overScan) * 2) + 1)) {
      const result = [];
      const getIndex = [];
      let newActiveIndex = activeIndex;
      const { type, direction } = this.scrollType;
      switch (type) {
        case 'scroll': {
          if (direction === 'left') newActiveIndex += 1;
          else newActiveIndex -= 1;
          break;
        }
        case 'arrows': {
          if (direction === 'next') newActiveIndex += 1;
          else newActiveIndex -= 1;
          break;
        }
        case 'dots': {
          if (direction === 'right') newActiveIndex += 1;
          else newActiveIndex -= 1;
          break;
        }
        case 'wheel': {
          if (direction === 'next') newActiveIndex += 1;
          else newActiveIndex -= 1;
          break;
        }
        case 'autoplay': {
          newActiveIndex += 1;
          break;
        }
        default:
          break;
      }
      let i = 0;
      for (; i < slidesToShow + overScan; i += 1) {
        if (i === 0) {
          const index = this.items.getIndex(newActiveIndex);
          getIndex.push(index);
        } else {
          const rightIndex = this.items.getIndex(newActiveIndex + i);
          const leftIndex = this.items.getIndex(newActiveIndex - i);
          getIndex.push(rightIndex);
          getIndex.unshift(leftIndex);
        }
      }
      if (this.endIndex >= 0 && typeof this.endIndex === 'number') {
        let buffer = 0;
        if (
          activeIndex + this.endIndex < this.newChildren.length + this.scrollDistance
          && activeIndex + this.endIndex >= this.newChildren.length - this.scrollDistance
          && (activeIndex >= this.newChildren.length - this.scrollDistance
          || this.endIndex >= this.newChildren.length - this.scrollDistance)
        ) {
          Eif (this.endIndex + activeIndex < this.newChildren.length) {
            if (this.endIndex < activeIndex) {
              buffer = this.newChildren.length - activeIndex + this.endIndex;
            } else {
              buffer = this.newChildren.length - this.endIndex + activeIndex;
            }
          } else if (this.endIndex < activeIndex) {
            buffer = (this.newChildren.length + this.scrollDistance) - activeIndex + this.endIndex;
          } else {
            buffer = (this.newChildren.length + this.scrollDistance) - this.endIndex + activeIndex;
          }
        } else {
          buffer = this.endIndex < activeIndex
            ? activeIndex - this.endIndex
            : this.endIndex - activeIndex;
        }
        for (let j = 0; j < buffer; j += 1) {
          const rightIndex = this.items.getIndex(newActiveIndex + i + j);
          const leftIndex = this.items.getIndex(newActiveIndex - i - j);
          switch (type) {
            case 'arrows': {
              if (direction === 'next') getIndex.push(rightIndex);
              else getIndex.unshift(leftIndex);
              break;
            }
            case 'dots': {
              if (direction === 'right') getIndex.push(rightIndex);
              else getIndex.unshift(leftIndex);
              break;
            }
            case 'wheel': {
              if (direction === 'next') getIndex.push(rightIndex);
              else getIndex.unshift(leftIndex);
              break;
            }
            case 'autoplay': {
              getIndex.push(rightIndex);
              break;
            }
            default:
              break;
          }
        }
      }
      getIndex.sort((a, b) => a - b);
      for (i = 0; i < getIndex.length; i += 1) {
        const childrenIndex = getIndex[i];
        const children = this.newChildren[childrenIndex];
        result.push(children);
      }
      return result;
    }
    return this.virtualList;
  }
 
  render() {
    const { height, settings, activeIndex } = this.state;
    const spec = { ...settings, ...this.prop };
    const { centerPadding, centerMode } = settings;
    const padding = typeof centerPadding === 'string' ? centerPadding : `${centerPadding}px`;
    /*  arrow  */
    const arrowProps = extractObject(spec, [
      'arrows',
      'arrowsScroll',
      'centerMode',
      'currentSlide',
      'slideCount',
      'slidesToShow',
      'prevArrow',
      'nextArrow',
      'arrowsBlock'
    ]);
    let prevArrow;
    let nextArrow;
    if (settings.arrows) {
      prevArrow = (
        <PrevArrow
          {...arrowProps}
          clickHandler={(options) => {
            this.beforeChangeTrigger = false;
            this.scrollType = {
              type: 'arrows',
              direction: 'prev'
            };
            this.scrollOptions = options;
            this.slickPrev(activeIndex - options.arrowsScroll);
          }}
        />
      );
      nextArrow = (
        <NextArrow
          {...arrowProps}
          clickHandler={(options) => {
            this.beforeChangeTrigger = false;
            this.scrollType = {
              type: 'arrows',
              direction: 'next'
            };
            this.scrollOptions = options;
            this.slickNext(activeIndex + options.arrowsScroll);
          }}
        />
      );
    }
 
    /*  Dots  */
    let dots;
    if (settings.dots === true && this.items) {
      Eif (this.items.length >= settings.slidesToShow) {
        const dotProps = extractObject(spec, [
          'dotsClass',
          'slidesToShow',
          'dotsScroll',
          'clickHandler',
          'children',
          'customPaging',
          'infinite',
          'appendDots'
        ]);
        const { pauseOnDotsHover } = settings;
        Object.assign(dotProps, {
          activeIndex,
          slideCount: this.items.length,
          clickHandler: (options) => {
            this.beforeChangeTrigger = false;
            let right = 0;
            let left = 0;
            let direction = null;
            if (activeIndex > options.index) {
              right = this.newChildren.length - activeIndex + options.index;
              left = activeIndex - options.index;
              direction = right < left ? 'right' : 'left';
            } else {
              right = options.index - activeIndex;
              left = this.newChildren.length - options.index + activeIndex;
              direction = right <= left ? 'right' : 'left';
            }
            this.scrollType = {
              type: 'dots',
              direction
            };
            this.scrollOptions = options;
            this.slickSet(options.index * options.dotsScroll);
          },
          onMouseEnter: pauseOnDotsHover ? this.onDotsLeave : null,
          onMouseOver: pauseOnDotsHover ? this.onDotsOver : null,
          onMouseLeave: pauseOnDotsHover ? this.onDotsLeave : null
        });
        dots = <Dots {...dotProps} />;
      }
    }
    const judge = this.items ? settings.slidesToShow < this.items.length : false;
    /*  Slide  */
    let component = (
      <Fragment>
        <div
          ref={(e) => {
            const { SliderRef } = this.state;
            if (!SliderRef && this.isMounted) {
              this.setRef(e);
            }
          }}
          className="carousel-initialized"
          style={{
            padding: centerMode ? `0 ${padding}` : 0
          }}
        >
          {!settings.unslick && judge ? prevArrow : ''}
          <div style={{ height: `${height}px` }} className="carousel-track">
            {this.rerender ? this.newChildren : this.virtualList}
          </div>
          {!settings.unslick && judge ? nextArrow : ''}
        </div>
        {!settings.unslick && judge ? dots : ''}
      </Fragment>
    );
    Iif (settings === 'unslick') {
      const className = `regular slider ${settings.className || ''}`;
      component = <div className={className}>{this.newChildren}</div>;
    }
    return (
      <div className={classNames(settings.className)}>{component}</div>
    );
  }
}
 
Slider.propTypes = propTypes;
Slider.defaultProps = defaultProps;
 
export default Slider;