"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

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

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

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

var _iconsReact = require("@wfp/icons-react");

var _Select = _interopRequireDefault(require("../Select"));

var _SelectItem = _interopRequireDefault(require("../SelectItem"));

var _array = require("../../tools/array");

var _excluded = ["backwardText", "className", "forwardText", "id", "itemsPerPageText", "itemsPerPageFollowsText", "itemRangeText", "pageRangeText", "pageSize", "pageSizesDisabled", "pageSizes", "itemText", "pageText", "pageNumberText", "pagesUnknown", "isLastPage", "pageInputDisabled", "totalItems", "onChange", "page"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var instanceId = 0;
/** Pagination is used for splitting up content or data into several pages, with a control for navigating to the next or previous page. */

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

  var _super = _createSuper(Pagination);

  function Pagination(props) {
    var _this;

    (0, _classCallCheck2.default)(this, Pagination);
    _this = _super.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleSizeChange", function (evt) {
      var pageSize = Number(evt.target.value);

      _this.setState({
        pageSize: pageSize,
        page: 1
      }, function () {});

      _this.props.onChange({
        page: 1,
        pageSize: pageSize
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handlePageChange", function (evt) {
      _this.setState({
        page: evt.target.value
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handlePageInputChange", function (evt) {
      var page = Number(evt.target.value);

      if (page > 0 && page <= Math.max(Math.ceil(_this.props.totalItems / _this.state.pageSize), 1)) {
        _this.setState({
          page: page
        });

        _this.props.onChange({
          page: page,
          pageSize: _this.state.pageSize
        });
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "incrementPage", function () {
      var page = _this.state.page + 1;

      _this.setState({
        page: page
      });

      _this.props.onChange({
        page: page,
        pageSize: _this.state.pageSize
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "decrementPage", function () {
      var page = _this.state.page - 1;

      _this.setState({
        page: page
      });

      _this.props.onChange({
        page: page,
        pageSize: _this.state.pageSize
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "renderSelectItems", function (total) {
      var counter = 1;
      var itemArr = [];

      while (counter <= total) {
        itemArr.push( /*#__PURE__*/_react.default.createElement(_SelectItem.default, {
          key: counter,
          value: counter,
          text: String(counter)
        }));
        counter++;
      }

      return itemArr;
    });
    var _this$props = _this.props,
        pageSizes = _this$props.pageSizes,
        _page = _this$props.page,
        _pageSize = _this$props.pageSize;
    _this.state = {
      page: _page,
      pageSize: pageSizes.includes(_pageSize) ? _pageSize : pageSizes[0],
      prevPageSizes: pageSizes,
      prevPage: _page,
      prevPageSize: _pageSize
    };
    _this.uniqueId = ++instanceId;
    return _this;
  }

  (0, _createClass2.default)(Pagination, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          backwardText = _this$props2.backwardText,
          className = _this$props2.className,
          forwardText = _this$props2.forwardText,
          id = _this$props2.id,
          itemsPerPageText = _this$props2.itemsPerPageText,
          itemsPerPageFollowsText = _this$props2.itemsPerPageFollowsText,
          itemRangeText = _this$props2.itemRangeText,
          pageRangeText = _this$props2.pageRangeText,
          pageSize = _this$props2.pageSize,
          pageSizesDisabled = _this$props2.pageSizesDisabled,
          pageSizes = _this$props2.pageSizes,
          itemText = _this$props2.itemText,
          pageText = _this$props2.pageText,
          pageNumberText = _this$props2.pageNumberText,
          pagesUnknown = _this$props2.pagesUnknown,
          isLastPage = _this$props2.isLastPage,
          pageInputDisabled = _this$props2.pageInputDisabled,
          totalItems = _this$props2.totalItems,
          onChange = _this$props2.onChange,
          pageNumber = _this$props2.page,
          other = (0, _objectWithoutProperties2.default)(_this$props2, _excluded);
      var statePage = this.state.page;
      var statePageSize = this.props.pageSize ? this.props.pageSize : this.state.pageSize;
      var classNames = (0, _classnames.default)('wfp--pagination', className);
      var backButtonClasses = (0, _classnames.default)('wfp--pagination__button', 'wfp--pagination__button--backward', {
        'wfp--pagination__button--no-index': pageInputDisabled
      });
      var inputId = id || this.uniqueId;
      var totalPages = Math.max(Math.ceil(totalItems / statePageSize), 1);
      var selectItems = this.renderSelectItems(totalPages);
      return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
        className: classNames
      }, other), /*#__PURE__*/_react.default.createElement("div", {
        className: "wfp--pagination__left"
      }, !pageSizesDisabled && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("span", {
        className: "wfp--pagination__text"
      }, itemsPerPageFollowsText || itemsPerPageText), /*#__PURE__*/_react.default.createElement(_Select.default, {
        id: "wfp-pagination-select-".concat(inputId),
        labelText: itemsPerPageText,
        hideLabel: true,
        inline: true,
        onChange: this.handleSizeChange // value={statePageSize}
        ,
        value: this.state.pageSize
      }, pageSizes.map(function (size) {
        return /*#__PURE__*/_react.default.createElement(_SelectItem.default, {
          key: size,
          value: size,
          text: String(size)
        });
      })), /*#__PURE__*/_react.default.createElement("span", {
        className: "wfp--pagination__text"
      }, "\xA0|\xA0\xA0")), /*#__PURE__*/_react.default.createElement("span", {
        className: "wfp--pagination__text"
      }, pagesUnknown ? itemText(statePageSize * (statePage - 1) + 1, statePage * statePageSize) : itemRangeText(Math.min(this.state.pageSize * (statePage - 1) + 1, totalItems), Math.min(statePage * this.state.pageSize, totalItems), totalItems))), /*#__PURE__*/_react.default.createElement("div", {
        className: "wfp--pagination__right wfp--pagination--inline"
      }, /*#__PURE__*/_react.default.createElement("span", {
        className: "wfp--pagination__text"
      }, pagesUnknown ? pageText(statePage) : pageRangeText(statePage, totalPages)), /*#__PURE__*/_react.default.createElement("button", {
        className: backButtonClasses,
        onClick: this.decrementPage,
        disabled: this.props.disabled || statePage === 1
      }, /*#__PURE__*/_react.default.createElement(_iconsReact.ChevronLeft16, {
        className: "wfp--pagination__button-icon",
        description: backwardText
      })), pageInputDisabled ? null : /*#__PURE__*/_react.default.createElement(_Select.default, {
        id: "wfp-pagination-select-".concat(inputId + 2),
        labelText: itemsPerPageText,
        hideLabel: true,
        inline: true,
        onChange: this.handlePageInputChange,
        value: statePage
      }, selectItems), /*#__PURE__*/_react.default.createElement("button", {
        className: "wfp--pagination__button wfp--pagination__button--forward",
        onClick: this.incrementPage,
        disabled: this.props.disabled || statePage === totalPages || isLastPage
      }, /*#__PURE__*/_react.default.createElement(_iconsReact.ChevronRight16, {
        className: "wfp--pagination__button-icon",
        description: forwardText
      }))));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(_ref, state) {
      var pageSizes = _ref.pageSizes,
          page = _ref.page,
          pageSize = _ref.pageSize;
      var prevPageSizes = state.prevPageSizes,
          prevPage = state.prevPage,
          prevPageSize = state.prevPageSize,
          currentPage = state.page,
          currentPageSize = state.pageSize;
      var pageSizesChanged = !(0, _array.equals)(pageSizes, prevPageSizes);
      var pageChanged = page !== prevPage;
      var pageSizeChanged = pageSize !== prevPageSize;
      return !pageSizesChanged && !pageChanged && !pageSizeChanged ? null : {
        page: pageSizesChanged ? 1 : pageChanged ? page : currentPage,
        pageSize: pageSizesChanged ? pageSizes[0] : pageSizeChanged ? pageSize : currentPageSize,
        prevPageSizes: pageSizes,
        prevPage: page,
        prevPageSize: pageSize
      };
    }
  }]);
  return Pagination;
}(_react.Component);

exports.default = Pagination;
(0, _defineProperty2.default)(Pagination, "propTypes", {
  /**
   * The description for the backward icon.
   */
  backwardText: _propTypes.default.string,

  /**
   * The CSS class names.
   */
  className: _propTypes.default.string,

  /**
   * The function returning a translatable text showing where the current page is,
   * in a manner of the range of items.
   */
  itemRangeText: _propTypes.default.func,

  /**
   * The description for the forward icon.
   */
  forwardText: _propTypes.default.string,

  /**
   * The unique ID of this component instance.
   */
  id: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]),

  /**
   * The translatable text indicating the number of items per page.
   */
  itemsPerPageText: _propTypes.default.string,

  /**
   * A variant of `itemsPerPageText`, with a sign indicating that the number follows, e.g. ':'.
   */
  itemsPerPageFollowsText: _propTypes.default.string,

  /**
   * A variant of `itemRangeText`, used if the total number of items is unknown.
   */
  itemText: _propTypes.default.func,

  /**
   * The callback function called when the current page changes.
   */
  onChange: _propTypes.default.func,
  pageNumberText: _propTypes.default.string,

  /**
   * A function returning PII showing where the current page is.
   */
  pageRangeText: _propTypes.default.func,

  /**
   * The translatable text showing the current page.
   */
  pageText: _propTypes.default.func,

  /**
   * The choices for `pageSize`.
   */
  pageSizes: _propTypes.default.arrayOf(_propTypes.default.number).isRequired,

  /**
   * `true` if ture the pageSizes should be not visible.
   */
  pageSizesDisabled: _propTypes.default.bool,

  /**
   * The total number of items.
   */
  totalItems: _propTypes.default.number,

  /**
   * `true` if the backward/forward buttons should be disabled.
   */
  disabled: _propTypes.default.bool,

  /**
   * The current page.
   */
  page: _propTypes.default.number,

  /**
   * The number dictating how many items a page contains.
   */
  pageSize: _propTypes.default.number,

  /**
   * `true` if the total number of items is unknown.
   */
  pagesUnknown: _propTypes.default.bool,

  /**
   * `true` if the current page should be the last page.
   */
  isLastPage: _propTypes.default.bool,

  /**
   * `true` if the select box to change the page should be disabled.
   */
  pageInputDisabled: _propTypes.default.bool
});
(0, _defineProperty2.default)(Pagination, "defaultProps", {
  backwardText: 'Backward',
  itemRangeText: function itemRangeText(min, max, total) {
    return "".concat(min, "-").concat(max, " of ").concat(total, " items");
  },
  forwardText: 'Forward',
  itemsPerPageText: 'Items per page:',
  pageNumberText: 'Page Number',
  pageRangeText: function pageRangeText(current, total) {
    return "".concat(current, " of ").concat(total, " pages");
  },
  disabled: false,
  page: 1,
  pagesUnknown: false,
  pageSizes: [10, 20, 50],
  isLastPage: false,
  pageInputDisabled: false,
  itemText: function itemText(min, max) {
    return "".concat(min, "-").concat(max, " items");
  },
  pageText: function pageText(page) {
    return "page ".concat(page);
  }
});