"use strict";

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

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

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

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

var _customPropTypes = require("../../utils/custom-prop-types");

var _Spinner = _interopRequireDefault(require("../Spinner"));

var _Link = _interopRequireDefault(require("../Link"));

var _lodash = _interopRequireDefault(require("lodash"));

var _flatten = _interopRequireDefault(require("lodash/flatten"));

var _Button = _interopRequireDefault(require("../Button"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var ELLIPSES_PLACEHOLDER = null;
var PAGE_NUMBER_PLACEHOLDER = "[pageNumber]";

var PaginationControls =
/*#__PURE__*/
function (_Component) {
  _inherits(PaginationControls, _Component);

  function PaginationControls() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, PaginationControls);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(PaginationControls)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_this), "handlePageChange", function (newPage) {
      return function () {
        var _this$props = _this.props,
            goToPage = _this$props.goToPage,
            isLoading = _this$props.isLoading;

        if (!isLoading) {
          goToPage(newPage);
        }
      };
    });

    return _this;
  }

  _createClass(PaginationControls, [{
    key: "getCoercedInputs",
    value: function getCoercedInputs() {
      var _this$props2 = this.props,
          currentPage = _this$props2.currentPage,
          totalSlots = _this$props2.totalSlots,
          totalPages = _this$props2.totalPages; // Ensure total pages is at least 2

      var sanitizedTotalPages = Math.max(totalPages, 2); // Ensure at least 7 slots

      var sanitizedTotalSlots = Math.min(Math.max(totalSlots, 7), sanitizedTotalPages); // Calculate number of numbers on either side of currentPage number
      // 5 represents the 5 guaranteed slots
      // (firstPage, beginning dots, currentPage, endingDots, lastPage)

      var buffer = Math.floor((sanitizedTotalSlots - 5) / 2); // Calculate max consecutive numbers (besides 1, lastPage, and ellipses)
      // 3 represents the 3 guaranteed slots when not in the middle state
      // (firstPage, endingDots, lastPage)

      var remainingSlotsToFill = sanitizedTotalSlots - 3; // Adjust current page to stay in range

      var sanitizedCurrentPage = Math.max(Math.min(currentPage, sanitizedTotalPages), 1);
      return {
        totalPages: sanitizedTotalPages,
        totalSlots: sanitizedTotalSlots,
        buffer: buffer,
        remainingSlotsToFill: remainingSlotsToFill,
        currentPage: sanitizedCurrentPage
      };
    }
  }, {
    key: "fillPageSlots",
    value: function fillPageSlots() {
      var _this$getCoercedInput = this.getCoercedInputs(),
          totalPages = _this$getCoercedInput.totalPages,
          totalSlots = _this$getCoercedInput.totalSlots,
          buffer = _this$getCoercedInput.buffer,
          remainingSlotsToFill = _this$getCoercedInput.remainingSlotsToFill,
          currentPage = _this$getCoercedInput.currentPage;

      var distanceFromCurrentPageToFront = currentPage - 1;
      var distanceFromCurrentPageToBack = totalPages - currentPage;
      var currentPageIsCloseToBack = distanceFromCurrentPageToBack + buffer <= remainingSlotsToFill;
      var currentPageIsCloseToFront = distanceFromCurrentPageToFront + buffer <= remainingSlotsToFill;
      var ellipsesRequired = totalPages > totalSlots;

      var pageNumbers = _lodash["default"] // Generate entire array of page numbers
      .times(totalPages, function (i) {
        return i + 1;
      }) // Filter down numbers to only the ones we want to show
      .filter(function (activePage) {
        var distanceBetweenCurrentAndActivePages = Math.abs(currentPage - activePage);
        var distanceBetweenActivePageAndFront = activePage - 1;
        var distanceBetweenActivePageAndBack = totalPages - activePage;

        if (activePage === 1 || activePage === currentPage || activePage === totalPages || !ellipsesRequired) {
          return true;
        }

        if (distanceBetweenCurrentAndActivePages <= buffer) {
          return true;
        }

        if (currentPageIsCloseToFront && distanceBetweenActivePageAndFront <= remainingSlotsToFill) {
          return true;
        }

        if (currentPageIsCloseToBack && distanceBetweenActivePageAndBack <= remainingSlotsToFill) {
          return true;
        }
      }) // Map over the number array and find spots to insert ellipses
      .map(function (val, idx, arr) {
        var frontEllipsesEligible = !currentPageIsCloseToFront && idx === 0;
        var backEllipsesEligible = !currentPageIsCloseToBack && idx === arr.length - 2;

        if (ellipsesRequired && (frontEllipsesEligible || backEllipsesEligible)) {
          return [val, ELLIPSES_PLACEHOLDER];
        }

        return val;
      });

      return (0, _flatten["default"])(pageNumbers);
    }
  }, {
    key: "getHrefUrl",
    value: function getHrefUrl(pageNumber) {
      var hrefBaseUrl = this.props.hrefBaseUrl;
      return hrefBaseUrl ? hrefBaseUrl.replace(PAGE_NUMBER_PLACEHOLDER, pageNumber) : undefined;
    }
  }, {
    key: "renderPageNumbers",
    value: function renderPageNumbers() {
      var _this2 = this;

      var _this$props3 = this.props,
          goToPage = _this$props3.goToPage,
          hrefBaseUrl = _this$props3.hrefBaseUrl,
          isLoading = _this$props3.isLoading;

      var _this$getCoercedInput2 = this.getCoercedInputs(),
          totalPages = _this$getCoercedInput2.totalPages,
          currentPage = _this$getCoercedInput2.currentPage;

      var controlSlots = this.fillPageSlots();
      return controlSlots.map(function (val, idx) {
        var ariaLabelString = "Page " + val;
        var ariaLabelSuffix = "";
        var isCurrent = val === currentPage;

        if (isCurrent) {
          ariaLabelSuffix = ", current page";
        } else if (val === totalPages) {
          ariaLabelSuffix = ", last page";
        }

        var content;

        if (val === ELLIPSES_PLACEHOLDER) {
          content = _react["default"].createElement("span", null, "...");
        } else if (hrefBaseUrl) {
          content = _react["default"].createElement(_Link["default"], {
            ariaLabel: ariaLabelString + ariaLabelSuffix,
            style: isCurrent ? "dark" : "default",
            href: _this2.getHrefUrl(val),
            onClick: !isCurrent && goToPage ? _this2.handlePageChange(val) : undefined,
            isDisabled: isLoading
          }, isCurrent ? _react["default"].createElement("strong", null, val) : val);
        } else {
          content = _react["default"].createElement(_Button["default"], {
            ariaLabel: ariaLabelString + ariaLabelSuffix,
            isDisabled: isLoading,
            style: "unstyled",
            onClick: !isCurrent && goToPage ? _this2.handlePageChange(val) : undefined
          }, _react["default"].createElement(_Link["default"], {
            style: isCurrent ? "dark" : "default",
            isDisabled: isLoading
          }, isCurrent ? _react["default"].createElement("strong", null, val) : val));
        }

        return _react["default"].createElement("li", {
          className: "push--sides",
          key: "link-".concat(idx)
        }, content);
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          className = _this$props4.className,
          currentPage = _this$props4.currentPage,
          goToPage = _this$props4.goToPage,
          hrefBaseUrl = _this$props4.hrefBaseUrl,
          isLoading = _this$props4.isLoading,
          testSection = _this$props4.testSection,
          totalPages = _this$props4.totalPages,
          totalSlots = _this$props4.totalSlots,
          props = _objectWithoutProperties(_this$props4, ["className", "currentPage", "goToPage", "hrefBaseUrl", "isLoading", "testSection", "totalPages", "totalSlots"]);

      var sanitizedTotalPages = Math.max(totalPages, 2);
      var previousButton;
      var nextButton;

      if (hrefBaseUrl) {
        previousButton = _react["default"].createElement(_Link["default"], {
          href: this.getHrefUrl(currentPage - 1),
          onClick: this.handlePageChange(Math.max(1, currentPage - 1)),
          isDisabled: currentPage <= 1 || isLoading,
          ariaLabel: "Previous Page"
        }, "Previous");
        nextButton = _react["default"].createElement(_Link["default"], {
          ariaLabel: "Next Page",
          href: this.getHrefUrl(currentPage + 1),
          onClick: this.handlePageChange(Math.min(sanitizedTotalPages, currentPage + 1)),
          isDisabled: currentPage >= sanitizedTotalPages || isLoading
        }, "Next");
      } else {
        previousButton = _react["default"].createElement(_Button["default"], {
          ariaLabel: "Previous Page",
          isDisabled: currentPage <= 1 || isLoading,
          style: "unstyled",
          onClick: this.handlePageChange(Math.max(1, currentPage - 1))
        }, _react["default"].createElement(_Link["default"], {
          isDisabled: currentPage <= 1 || isLoading
        }, "Previous"));
        nextButton = _react["default"].createElement(_Button["default"], {
          ariaLabel: "Next Page",
          isDisabled: currentPage >= sanitizedTotalPages || isLoading,
          style: "unstyled",
          onClick: this.handlePageChange(Math.min(sanitizedTotalPages, currentPage + 1))
        }, _react["default"].createElement(_Link["default"], {
          isDisabled: currentPage >= sanitizedTotalPages || isLoading
        }, "Next"));
      }

      return _react["default"].createElement("nav", _extends({
        className: (0, _classnames["default"])("oui-pagination-controls", className),
        "data-test-section": testSection
      }, props), isLoading && _react["default"].createElement(_Spinner["default"], {
        size: "tiny"
      }), _react["default"].createElement("ul", {
        className: "flex flex-justified--center flex-align--center"
      }, _react["default"].createElement("li", {
        className: "push--sides"
      }, previousButton), this.renderPageNumbers(), _react["default"].createElement("li", {
        className: "push--sides"
      }, nextButton)));
    }
  }]);

  return PaginationControls;
}(_react.Component);

PaginationControls.propTypes = {
  /** CSS class names. */
  className: _propTypes["default"].string,

  /** Sets the current page number */
  currentPage: _propTypes["default"].number.isRequired,

  /** Function that is called when a pagination link is clicked */
  goToPage: _propTypes["default"].func,
  // eslint-disable-next-line valid-jsdoc

  /**
   * Base URL to use for the Link's href.
   * Must include the string "[pageNumber]"
   */
  hrefBaseUrl: function hrefBaseUrl(props, propName, componentName) {
    if (props[propName] && typeof props[propName] !== "string") {
      return new Error("Invalid prop `" + propName + "` supplied to" + " `" + componentName + "`. Must be of type string.");
    } else if (props[propName] && !props[propName].includes(PAGE_NUMBER_PLACEHOLDER)) {
      return new Error("Invalid prop '" + propName + "' supplied to" + " '" + componentName + "'. Must contain the string '".concat(PAGE_NUMBER_PLACEHOLDER, "'."));
    }
  },

  /** Sets the total number of pages */
  isLoading: _propTypes["default"].bool,

  /** Hook for automated JavaScript tests */
  testSection: _propTypes["default"].string,

  /** Sets the total number of pages. Must be >=2 */
  totalPages: (0, _customPropTypes.checkPropIsGreaterThanOrEqualTo)(2, true),

  /**
   * Sets the total number of spots allowed
   * between the Previous and Next buttons.
   * Must be >= 7, default is 9
   */
  totalSlots: (0, _customPropTypes.checkPropIsGreaterThanOrEqualTo)(7, false)
};
PaginationControls.defaultProps = {
  testSection: "",
  totalSlots: 9
};
var _default = PaginationControls;
exports["default"] = _default;