"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _Pager = _interopRequireDefault(require("./Pager"));

var _Options = _interopRequireDefault(require("./Options"));

var _KeyCode = _interopRequireDefault(require("./KeyCode"));

var _zh_CN = _interopRequireDefault(require("./locale/zh_CN"));

function isInteger(value) {
  return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
}

function defaultItemRender(page, type, element) {
  return element;
}

var Pagination = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(Pagination, _Component);

  var _super = (0, _createSuper2["default"])(Pagination);

  function Pagination(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Pagination);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "savePaginationNode", function (node) {
      _this.paginationNode = node;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "calculatePage", function (p) {
      var pageSize = p;

      if (typeof pageSize === 'undefined') {
        pageSize = _this.state.pageSize;
      }

      return Math.floor((_this.props.total - 1) / pageSize) + 1;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "isValid", function (page) {
      return isInteger(page) && page >= 1 && page !== _this.state.current;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleKeyDown", function (e) {
      if (e.keyCode === _KeyCode["default"].ARROW_UP || e.keyCode === _KeyCode["default"].ARROW_DOWN) {
        e.preventDefault();
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleKeyUp", function (e) {
      var inputValue = e.target.value;
      var currentInputValue = _this.state.currentInputValue;
      var value;

      if (inputValue === '') {
        value = inputValue;
      } else if (isNaN(Number(inputValue))) {
        value = currentInputValue;
      } else {
        value = Number(inputValue);
      }

      if (value !== currentInputValue) {
        _this.setState({
          currentInputValue: value
        });
      }

      if (e.keyCode === _KeyCode["default"].ENTER) {
        _this.handleChange(value);
      } else if (e.keyCode === _KeyCode["default"].ARROW_UP) {
        _this.handleChange(value - 1);
      } else if (e.keyCode === _KeyCode["default"].ARROW_DOWN) {
        _this.handleChange(value + 1);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changePageSize", function (size) {
      var current = _this.state.current;

      var newCurrent = _this.calculatePage(size);

      current = current > newCurrent ? newCurrent : current; // fix the issue:
      // Once 'total' is 0, 'current' in 'onShowSizeChange' is 0, which is not correct.

      if (newCurrent === 0) {
        current = _this.state.current;
      }

      if (typeof size === 'number') {
        if (!('pageSize' in _this.props)) {
          _this.setState({
            pageSize: size
          });
        }

        if (!('current' in _this.props)) {
          _this.setState({
            current: current,
            currentInputValue: current
          });
        }
      }

      _this.props.onShowSizeChange(current, size);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleChange", function (p) {
      var page = p;

      if (_this.isValid(page)) {
        if (page > _this.calculatePage()) {
          page = _this.calculatePage();
        }

        if (!('current' in _this.props)) {
          _this.setState({
            current: page,
            currentInputValue: page
          });
        }

        var pageSize = _this.state.pageSize;

        _this.props.onChange(page, pageSize);

        return page;
      }

      return _this.state.current;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "first", function () {
      if (_this.hasPrev()) {
        _this.handleChange(1);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "last", function () {
      if (_this.hasNext()) {
        _this.handleChange(_this.calculatePage());
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "prev", function () {
      if (_this.hasPrev()) {
        _this.handleChange(_this.state.current - 1);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "next", function () {
      if (_this.hasNext()) {
        _this.handleChange(_this.state.current + 1);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "jumpPrev", function () {
      _this.handleChange(_this.getJumpPrevPage());
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "jumpNext", function () {
      _this.handleChange(_this.getJumpNextPage());
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hasPrev", function () {
      return _this.state.current > 1;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hasNext", function () {
      return _this.state.current < _this.calculatePage();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnter", function (event, callback) {
      if (event.key === 'Enter' || event.charCode === 13) {
        for (var _len = arguments.length, restParams = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          restParams[_key - 2] = arguments[_key];
        }

        callback.apply(void 0, restParams);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterFirst", function (e) {
      _this.runIfEnter(e, _this.first);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterLast", function (e) {
      _this.runIfEnter(e, _this.last);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterPrev", function (e) {
      _this.runIfEnter(e, _this.prev);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterNext", function (e) {
      _this.runIfEnter(e, _this.next);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterJumpPrev", function (e) {
      _this.runIfEnter(e, _this.jumpPrev);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "runIfEnterJumpNext", function (e) {
      _this.runIfEnter(e, _this.jumpNext);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleGoTO", function (e) {
      if (e.keyCode === _KeyCode["default"].ENTER || e.type === 'click') {
        _this.handleChange(_this.state.currentInputValue);
      }
    });
    var hasOnChange = props.onChange !== _noop["default"];
    var hasCurrent = ('current' in props);

    if (hasCurrent && !hasOnChange) {
      console.warn('Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.'); // eslint-disable-line
    }

    var _current = props.defaultCurrent;

    if ('current' in props) {
      _current = props.current;
    }

    var _pageSize = props.defaultPageSize;

    if ('pageSize' in props) {
      _pageSize = props.pageSize;
    }

    _this.state = {
      current: _current,
      currentInputValue: _current,
      pageSize: _pageSize
    };
    return _this;
  }

  (0, _createClass2["default"])(Pagination, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if ('current' in nextProps) {
        this.setState({
          current: nextProps.current,
          currentInputValue: nextProps.current
        });
      }

      if ('pageSize' in nextProps) {
        var newState = {};
        var current = this.state.current;
        var newCurrent = this.calculatePage(nextProps.pageSize);
        current = current > newCurrent ? newCurrent : current;

        if (!('current' in nextProps)) {
          newState.current = current;
          newState.currentInputValue = current;
        }

        newState.pageSize = nextProps.pageSize;
        this.setState(newState);
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      // When current page change, fix focused style of prev item
      var prefixCls = this.props.prefixCls;

      if (prevState.current !== this.state.current && this.paginationNode) {
        var lastCurrentNode = this.paginationNode.querySelector(".".concat(prefixCls, "-item-").concat(prevState.current));

        if (lastCurrentNode && document.activeElement === lastCurrentNode) {
          lastCurrentNode.blur();
        }
      }
    }
  }, {
    key: "getJumpPrevPage",
    value: function getJumpPrevPage() {
      return Math.max(1, this.state.current - (this.props.showLessItems ? 3 : 5));
    }
  }, {
    key: "getJumpNextPage",
    value: function getJumpNextPage() {
      return Math.min(this.calculatePage(), this.state.current + (this.props.showLessItems ? 3 : 5));
    }
  }, {
    key: "render",
    value: function render() {
      // When hideOnSinglePage is true and there is only 1 page, hide the pager
      if (this.props.hideOnSinglePage === true && this.props.total <= this.state.pageSize) {
        return null;
      }

      var props = this.props;
      var locale = props.locale;
      var prefixCls = props.prefixCls;
      var allPages = this.calculatePage();
      var pagerList = [];
      var jumpPrev = null;
      var jumpNext = null;
      var firstPager = null;
      var lastPager = null;
      var gotoButton = null;
      var goButton = props.showQuickJumper && props.showQuickJumper.goButton;
      var pageBufferSize = props.showLessItems ? 1 : 2;
      var _this$state = this.state,
          current = _this$state.current,
          pageSize = _this$state.pageSize;
      var prevPage = current - 1 > 0 ? current - 1 : 0;
      var nextPage = current + 1 < allPages ? current + 1 : allPages;
      var dataOrAriaAttributeProps = Object.keys(props).reduce(function (prev, key) {
        if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role') {
          prev[key] = props[key];
        }

        return prev;
      }, {});

      if (props.simple) {
        if (goButton) {
          if (typeof goButton === 'boolean') {
            gotoButton = /*#__PURE__*/_react["default"].createElement("button", {
              type: "button",
              onClick: this.handleGoTO,
              onKeyUp: this.handleGoTO
            }, locale.jump_to_confirm);
          } else {
            gotoButton = /*#__PURE__*/_react["default"].createElement("span", {
              onClick: this.handleGoTO,
              onKeyUp: this.handleGoTO
            }, goButton);
          }

          gotoButton = /*#__PURE__*/_react["default"].createElement("li", {
            title: props.showTitle ? "".concat(locale.jump_to).concat(this.state.current, "/").concat(allPages) : null,
            className: "".concat(prefixCls, "-simple-pager")
          }, gotoButton);
        }

        return /*#__PURE__*/_react["default"].createElement("ul", (0, _extends2["default"])({
          className: "".concat(prefixCls, " ").concat(prefixCls, "-simple ").concat(props.className),
          style: props.style,
          ref: this.savePaginationNode
        }, dataOrAriaAttributeProps), /*#__PURE__*/_react["default"].createElement("li", {
          title: props.showTitle ? locale.prev_page : null,
          onClick: this.prev,
          tabIndex: this.hasPrev() ? 0 : null,
          onKeyPress: this.runIfEnterPrev,
          className: "".concat(this.hasPrev() ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-prev"),
          "aria-disabled": !this.hasPrev()
        }, props.itemRender(prevPage, 'prev', /*#__PURE__*/_react["default"].createElement("a", {
          className: "".concat(prefixCls, "-item-link")
        }), !this.hasPrev(), 'small')), /*#__PURE__*/_react["default"].createElement("li", {
          title: props.showTitle ? "".concat(this.state.current, "/").concat(allPages) : null,
          className: "".concat(prefixCls, "-simple-pager")
        }, /*#__PURE__*/_react["default"].createElement("input", {
          type: "text",
          value: this.state.currentInputValue,
          onKeyDown: this.handleKeyDown,
          onKeyUp: this.handleKeyUp,
          onChange: this.handleKeyUp,
          size: "3"
        }), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-slash")
        }, "\uFF0F"), allPages), /*#__PURE__*/_react["default"].createElement("li", {
          title: props.showTitle ? locale.next_page : null,
          onClick: this.next,
          tabIndex: this.hasPrev() ? 0 : null,
          onKeyPress: this.runIfEnterNext,
          className: "".concat(this.hasNext() ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-next"),
          "aria-disabled": !this.hasNext()
        }, props.itemRender(nextPage, 'next', /*#__PURE__*/_react["default"].createElement("a", {
          className: "".concat(prefixCls, "-item-link")
        }), !this.hasNext(), 'small')), gotoButton);
      }

      if (allPages <= 5 + pageBufferSize * 2) {
        for (var i = 1; i <= allPages; i++) {
          var active = this.state.current === i;
          pagerList.push( /*#__PURE__*/_react["default"].createElement(_Pager["default"], {
            size: props.size,
            locale: locale,
            rootPrefixCls: prefixCls,
            onClick: this.handleChange,
            onKeyPress: this.runIfEnter,
            key: i,
            page: i,
            active: active,
            showTitle: props.showTitle,
            itemRender: props.itemRender
          }));
        }
      } else {
        var prevItemTitle = props.showLessItems ? locale.prev_3 : locale.prev_5;
        var nextItemTitle = props.showLessItems ? locale.next_3 : locale.next_5;

        if (props.showPrevNextJumpers) {
          var _props$renderJumper = props.renderJumper,
              renderJumper = _props$renderJumper === void 0 ? function () {
            return '•••';
          } : _props$renderJumper;
          jumpPrev = /*#__PURE__*/_react["default"].createElement("li", {
            title: props.showTitle ? prevItemTitle : null,
            key: "prev",
            onClick: this.jumpPrev,
            tabIndex: "0",
            onKeyPress: this.runIfEnterJumpPrev,
            className: "".concat(prefixCls, "-jump-prev")
          }, props.itemRender(this.getJumpPrevPage(), 'jump-prev', /*#__PURE__*/_react["default"].createElement("a", {
            className: "".concat(prefixCls, "-item-link")
          }, renderJumper()), props.size));
          jumpNext = /*#__PURE__*/_react["default"].createElement("li", {
            title: props.showTitle ? nextItemTitle : null,
            key: "next",
            tabIndex: "0",
            onClick: this.jumpNext,
            onKeyPress: this.runIfEnterJumpNext,
            className: "".concat(prefixCls, "-jump-next")
          }, props.itemRender(this.getJumpNextPage(), 'jump-next', /*#__PURE__*/_react["default"].createElement("a", {
            className: "".concat(prefixCls, "-item-link")
          }, renderJumper()), props.size));
        }

        lastPager = /*#__PURE__*/_react["default"].createElement(_Pager["default"], {
          size: props.size,
          locale: props.locale,
          last: true,
          rootPrefixCls: prefixCls,
          onClick: this.handleChange,
          onKeyPress: this.runIfEnter,
          key: allPages,
          page: allPages,
          active: false,
          showTitle: props.showTitle,
          itemRender: props.itemRender
        });
        firstPager = /*#__PURE__*/_react["default"].createElement(_Pager["default"], {
          size: props.size,
          locale: props.locale,
          rootPrefixCls: prefixCls,
          onClick: this.handleChange,
          onKeyPress: this.runIfEnter,
          key: 1,
          page: 1,
          active: false,
          showTitle: props.showTitle,
          itemRender: props.itemRender
        });
        var left = Math.max(1, current - pageBufferSize);
        var right = Math.min(current + pageBufferSize, allPages);

        if (current - 1 <= pageBufferSize) {
          right = 1 + pageBufferSize * 2;
        }

        if (allPages - current <= pageBufferSize) {
          left = allPages - pageBufferSize * 2;
        }

        for (var _i = left; _i <= right; _i++) {
          var _active = current === _i;

          pagerList.push( /*#__PURE__*/_react["default"].createElement(_Pager["default"], {
            size: props.size,
            locale: props.locale,
            rootPrefixCls: prefixCls,
            onClick: this.handleChange,
            onKeyPress: this.runIfEnter,
            key: _i,
            page: _i,
            active: _active,
            showTitle: props.showTitle,
            itemRender: props.itemRender
          }));
        }

        if (current - 1 >= pageBufferSize * 2 && current !== 1 + 2) {
          pagerList[0] = /*#__PURE__*/(0, _react.cloneElement)(pagerList[0], {
            className: "".concat(prefixCls, "-item-after-jump-prev")
          });
          pagerList.unshift(jumpPrev);
        }

        if (allPages - current >= pageBufferSize * 2 && current !== allPages - 2) {
          pagerList[pagerList.length - 1] = /*#__PURE__*/(0, _react.cloneElement)(pagerList[pagerList.length - 1], {
            className: "".concat(prefixCls, "-item-before-jump-next")
          });
          pagerList.push(jumpNext);
        }

        if (left !== 1) {
          pagerList.unshift(firstPager);
        }

        if (right !== allPages) {
          pagerList.push(lastPager);
        }
      }

      var totalText = null;

      if (props.showTotal) {
        totalText = /*#__PURE__*/_react["default"].createElement("li", {
          className: "".concat(prefixCls, "-total-text")
        }, props.showTotal(props.total, [(current - 1) * pageSize + 1, current * pageSize > props.total ? props.total : current * pageSize]));
      }

      if (props.tiny) {
        var fistDisabled = !this.hasPrev();
        var lastDisabled = !this.hasNext();
        firstPager = /*#__PURE__*/_react["default"].createElement("li", {
          title: props.showTitle ? locale.first_page : null,
          onClick: this.first,
          tabIndex: fistDisabled ? null : 0,
          onKeyPress: this.runIfEnterFirst,
          className: "".concat(!fistDisabled ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-first"),
          "aria-disabled": fistDisabled
        }, props.itemRender(1, 'first', /*#__PURE__*/_react["default"].createElement("a", {
          className: "".concat(prefixCls, "-item-link")
        }), fistDisabled, props.size));
        lastPager = /*#__PURE__*/_react["default"].createElement("li", {
          title: props.showTitle ? locale.last_page : null,
          onClick: this.last,
          tabIndex: lastDisabled ? null : 0,
          onKeyPress: this.runIfEnterLast,
          className: "".concat(!lastDisabled ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-last"),
          "aria-disabled": lastDisabled
        }, props.itemRender(allPages, 'last', /*#__PURE__*/_react["default"].createElement("a", {
          className: "".concat(prefixCls, "-item-link")
        }), lastDisabled, props.size));
      }

      var prevDisabled = !this.hasPrev();
      var nextDisabled = !this.hasNext();

      var sizeChanger = /*#__PURE__*/_react["default"].createElement(_Options["default"], {
        locale: props.locale,
        rootPrefixCls: prefixCls,
        selectComponentClass: props.selectComponentClass,
        selectProps: props.selectProps,
        changeSize: this.props.showSizeChanger ? this.changePageSize : null,
        current: this.state.current,
        pageSize: this.state.pageSize,
        pageSizeOptions: this.props.pageSizeOptions,
        quickGo: this.props.showQuickJumper ? this.handleChange : null,
        goButton: goButton,
        buildOptionText: props.sizeChangerOptionText,
        changeSizeLabel: this.props.showSizeChangerLabel
      });

      var classString = (0, _classnames["default"])(prefixCls, props.className, (0, _defineProperty2["default"])({}, "".concat(prefixCls, "-tiny"), props.tiny));
      return /*#__PURE__*/_react["default"].createElement("ul", (0, _extends2["default"])({
        className: classString,
        style: props.style,
        unselectable: "unselectable",
        ref: this.savePaginationNode
      }, dataOrAriaAttributeProps), props.tiny && sizeChanger, totalText, props.tiny && firstPager, /*#__PURE__*/_react["default"].createElement("li", {
        title: props.showTitle ? locale.prev_page : null,
        onClick: this.prev,
        tabIndex: prevDisabled ? null : 0,
        onKeyPress: this.runIfEnterPrev,
        className: "".concat(!prevDisabled ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-prev"),
        "aria-disabled": prevDisabled
      }, props.itemRender(prevPage, 'prev', /*#__PURE__*/_react["default"].createElement("a", {
        className: "".concat(prefixCls, "-item-link")
      }), prevDisabled, props.size)), !props.tiny && pagerList, /*#__PURE__*/_react["default"].createElement("li", {
        title: props.showTitle ? locale.next_page : null,
        onClick: this.next,
        tabIndex: nextDisabled ? null : 0,
        onKeyPress: this.runIfEnterNext,
        className: "".concat(!nextDisabled ? '' : "".concat(prefixCls, "-disabled"), " ").concat(prefixCls, "-next"),
        "aria-disabled": nextDisabled
      }, props.itemRender(nextPage, 'next', /*#__PURE__*/_react["default"].createElement("a", {
        className: "".concat(prefixCls, "-item-link")
      }), nextDisabled, props.size)), props.tiny ? lastPager : sizeChanger);
    }
  }]);
  return Pagination;
}(_react.Component);

exports["default"] = Pagination;
(0, _defineProperty2["default"])(Pagination, "defaultProps", {
  defaultCurrent: 1,
  total: 0,
  defaultPageSize: 10,
  onChange: _noop["default"],
  className: '',
  selectProps: {
    prefixCls: 'rc-select'
  },
  prefixCls: 'rc-pagination',
  selectComponentClass: null,
  hideOnSinglePage: false,
  showPrevNextJumpers: true,
  showQuickJumper: false,
  showSizeChanger: false,
  showLessItems: false,
  showTitle: true,
  onShowSizeChange: _noop["default"],
  locale: _zh_CN["default"],
  style: {},
  itemRender: defaultItemRender
});
//# sourceMappingURL=Pagination.js.map
