UNPKG

optimizely-oui

Version:

Optimizely's Component Library.

329 lines (273 loc) 15 kB
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; } /* eslint-disable no-script-url */ import React, { Component } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import { checkPropIsGreaterThanOrEqualTo } from "../../utils/custom-prop-types"; import Spinner from "../Spinner"; import Link from "../Link"; import _ from "lodash"; import flatten from "lodash/flatten"; import Button from "../Button"; 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 = _ // 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 flatten(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.createElement("span", null, "..."); } else if (hrefBaseUrl) { content = React.createElement(Link, { ariaLabel: ariaLabelString + ariaLabelSuffix, style: isCurrent ? "dark" : "default", href: _this2.getHrefUrl(val), onClick: !isCurrent && goToPage ? _this2.handlePageChange(val) : undefined, isDisabled: isLoading }, isCurrent ? React.createElement("strong", null, val) : val); } else { content = React.createElement(Button, { ariaLabel: ariaLabelString + ariaLabelSuffix, isDisabled: isLoading, style: "unstyled", onClick: !isCurrent && goToPage ? _this2.handlePageChange(val) : undefined }, React.createElement(Link, { style: isCurrent ? "dark" : "default", isDisabled: isLoading }, isCurrent ? React.createElement("strong", null, val) : val)); } return React.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.createElement(Link, { href: this.getHrefUrl(currentPage - 1), onClick: this.handlePageChange(Math.max(1, currentPage - 1)), isDisabled: currentPage <= 1 || isLoading, ariaLabel: "Previous Page" }, "Previous"); nextButton = React.createElement(Link, { ariaLabel: "Next Page", href: this.getHrefUrl(currentPage + 1), onClick: this.handlePageChange(Math.min(sanitizedTotalPages, currentPage + 1)), isDisabled: currentPage >= sanitizedTotalPages || isLoading }, "Next"); } else { previousButton = React.createElement(Button, { ariaLabel: "Previous Page", isDisabled: currentPage <= 1 || isLoading, style: "unstyled", onClick: this.handlePageChange(Math.max(1, currentPage - 1)) }, React.createElement(Link, { isDisabled: currentPage <= 1 || isLoading }, "Previous")); nextButton = React.createElement(Button, { ariaLabel: "Next Page", isDisabled: currentPage >= sanitizedTotalPages || isLoading, style: "unstyled", onClick: this.handlePageChange(Math.min(sanitizedTotalPages, currentPage + 1)) }, React.createElement(Link, { isDisabled: currentPage >= sanitizedTotalPages || isLoading }, "Next")); } return React.createElement("nav", _extends({ className: classNames("oui-pagination-controls", className), "data-test-section": testSection }, props), isLoading && React.createElement(Spinner, { size: "tiny" }), React.createElement("ul", { className: "flex flex-justified--center flex-align--center" }, React.createElement("li", { className: "push--sides" }, previousButton), this.renderPageNumbers(), React.createElement("li", { className: "push--sides" }, nextButton))); } }]); return PaginationControls; }(Component); PaginationControls.propTypes = { /** CSS class names. */ className: PropTypes.string, /** Sets the current page number */ currentPage: PropTypes.number.isRequired, /** Function that is called when a pagination link is clicked */ goToPage: PropTypes.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.bool, /** Hook for automated JavaScript tests */ testSection: PropTypes.string, /** Sets the total number of pages. Must be >=2 */ totalPages: checkPropIsGreaterThanOrEqualTo(2, true), /** * Sets the total number of spots allowed * between the Previous and Next buttons. * Must be >= 7, default is 9 */ totalSlots: checkPropIsGreaterThanOrEqualTo(7, false) }; PaginationControls.defaultProps = { testSection: "", totalSlots: 9 }; export default PaginationControls;