"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;exports.__esModule = true;exports.PagingDataTids = exports.Paging = void 0;var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));var _react = _interopRequireDefault(require("react"));
var _globalObject = require("@skbkontur/global-object");

var _isInstanceOf = require("../../lib/isInstanceOf");
var _identifiers = require("../../lib/events/keyboard/identifiers");
var _decorators = require("../../lib/locale/decorators");

var _keyListener = require("../../lib/events/keyListener");
var _utils = require("../../lib/utils");
var _client = require("../../lib/client");
var _ThemeContext = require("../../lib/theming/ThemeContext");

var _ThemeHelpers = require("../../lib/theming/ThemeHelpers");

var _CommonWrapper = require("../../internal/CommonWrapper");
var _Emotion = require("../../lib/theming/Emotion");

var _rootNode = require("../../lib/rootNode");
var _createPropsGetter = require("../../lib/createPropsGetter");
var _getVisualStateDataAttributes = require("../../internal/CommonWrapper/utils/getVisualStateDataAttributes");
var _ResponsiveLayout = require("../ResponsiveLayout");


var _Paging2 = require("./Paging.styles");
var NavigationHelper = _interopRequireWildcard(require("./NavigationHelper"));
var _PagingHelper = require("./PagingHelper");

var _locale = require("./locale");
var _PagingDefaultComponent = require("./PagingDefaultComponent");
var _ForwardIcon = require("./ForwardIcon");
var _DotsIcon = require("./DotsIcon");var _dec, _class, _Paging;

var IGNORE_EVENT_TAGS = ['input', 'textarea'];






























































var PagingDataTids = exports.PagingDataTids = {
  root: 'Paging__root',
  dots: 'Paging__dots',
  forwardLink: 'Paging__forwardLink',
  pageLinkWrapper: 'Paging__pageLinkWrapper',
  pageLink: 'Paging__pageLink'
};










/**
 * Постраничная навигация `Paging` (пейджинг или пагинация) — способ представления большого количества однородной информации, когда контент разбивается на страницы.
 */var


Paging = exports.Paging = (_dec = (0, _decorators.locale)('Paging', _locale.PagingLocaleHelper), (0, _rootNode.rootNode)(_class = _dec(_class = (_Paging = /*#__PURE__*/function (_React$PureComponent) {function Paging() {var _this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}_this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;_this.








    getProps = (0, _createPropsGetter.createPropsGetter)(Paging.defaultProps);_this.








    state = {
      focusedByTab: false,
      focusedItem: null,
      keyboardControl: _this.getProps().useGlobalListener
    };_this.





    addedGlobalListener = false;_this.
    container = null;_this.















































































    renderItem = function (item, index) {
      var focused = _this.getFocusedItem() === item;
      switch (item) {
        case '.':{
            var key = "dots" + (index < 5 ? 'Left' : 'Right');
            return _this.renderDots(key);
          }
        case 'forward':{
            var disabled = _this.isItemDisabled(item);
            return _this.renderForwardLink(disabled, focused);
          }
        default:{
            var active = _this.props.activePage === item;
            return _this.renderPageLink(item, active, focused);
          }
      }
    };_this.

    renderDots = function (key) {var _cx;
      return /*#__PURE__*/(
        _react.default.createElement("span", {
          "data-tid": PagingDataTids.dots,
          key: key,
          className: (0, _Emotion.cx)(_Paging2.styles.dots(_this.theme), _this.sizeClassNames.dots, (_cx = {}, _cx[
          _Paging2.styles.dotsDisabled(_this.theme)] = _this.props.disabled, _cx)
          ) },

        _this.getDotsIcon()
        ));

    };_this.

    renderForwardLink = function (disabled, focused) {var _cx2;
      var classNames = (0, _Emotion.cx)(
        _Paging2.styles.pageLink(_this.theme),
        _this.sizeClassNames.pageLink,
        _Paging2.styles.forwardLink(_this.theme),
        _this.sizeClassNames.forwardLink, (_cx2 = {}, _cx2[

        _Paging2.styles.pageLinkFocused(_this.theme)] = focused, _cx2[
        _Paging2.styles.forwardLinkDisabled(_this.theme)] = disabled || _this.props.disabled, _cx2)

      );
      var Component = _this.getProps().component;
      var forward = _this.locale.forward;

      var forwardIcon = _this.getForwardIcon();

      return /*#__PURE__*/(
        _react.default.createElement(Component, (0, _extends2.default)({
          key: 'forward',
          "data-tid": PagingDataTids.forwardLink,
          active: false,
          className: classNames,
          onClick: disabled ? _utils.emptyHandler : _this.goForward,
          tabIndex: -1,
          pageNumber: 'forward' },
        (0, _getVisualStateDataAttributes.getVisualStateDataAttributes)({ disabled: disabled })),

        !_this.isMobile && (_this.props.caption || forward),
        forwardIcon
        ));

    };_this.

    renderPageLink = function (pageNumber, active, focused) {var _cx3;
      var disabled = _this.props.disabled;
      var classNames = (0, _Emotion.cx)(_Paging2.styles.pageLink(_this.theme), _this.sizeClassNames.pageLink, (_cx3 = {}, _cx3[
      _Paging2.styles.pageLinkFocused(_this.theme)] = focused, _cx3[
      _Paging2.styles.pageLinkDisabled(_this.theme)] = disabled, _cx3[
      _Paging2.styles.pageLinkCurrent(_this.theme)] = active, _cx3[
      _Paging2.styles.pageLinkCurrentDisabled(_this.theme)] = active && disabled, _cx3)
      );
      var Component = _this.getProps().component;
      var handleClick = function handleClick() {return _this.goToPage(pageNumber);};

      return /*#__PURE__*/(
        _react.default.createElement("span", (0, _extends2.default)({
          "data-tid": PagingDataTids.pageLinkWrapper,
          key: pageNumber,
          className: _Paging2.styles.pageLinkWrapper() },
        (0, _getVisualStateDataAttributes.getVisualStateDataAttributes)({ active: active, disabled: disabled }), {
          onMouseDown: _this.handleMouseDownPageLink }), /*#__PURE__*/

        _react.default.createElement(Component, {
          "data-tid": PagingDataTids.pageLink,
          active: active,
          className: classNames,
          onClick: handleClick,
          tabIndex: -1,
          pageNumber: pageNumber },

        pageNumber
        ),
        active && !_this.isMobile && _this.renderNavigationHint()
        ));

    };_this.

    renderNavigationHint = function () {
      if (_this.props.withoutNavigationHint) {
        return null;
      }

      var keyboardControl = _this.state.keyboardControl;
      var canGoBackward = _this.canGoBackward();
      var canGoForward = _this.canGoForward();

      var hint = null;
      if (keyboardControl && (canGoBackward || canGoForward)) {
        hint = /*#__PURE__*/
        _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/
        _react.default.createElement("span", { className: canGoBackward ? '' : _Paging2.styles.transparent() }, '←'), /*#__PURE__*/
        _react.default.createElement("span", null, NavigationHelper.getKeyName(_this.theme)), /*#__PURE__*/
        _react.default.createElement("span", { className: canGoForward ? '' : _Paging2.styles.transparent() }, '→')
        );

      }
      return /*#__PURE__*/_react.default.createElement("div", { className: _Paging2.styles.pageLinkHint(_this.theme) }, hint);
    };_this.

    handleMouseDown = function () {
      _this.setState({ focusedByTab: false, focusedItem: null });
    };_this.

    handleMouseDownPageLink = function () {
      if (_client.isIE11) {
        // Клик по span внутри контейнера с tabindex="0" переносит фокус именно на этот span.
        // Поэтому горячие клавиши работают пока span существует на странице.
        _globalObject.globalObject.setTimeout(function () {return _this.container && _this.container.focus();}, 0);
      }
    };_this.

    handleKeyDown = function (e) {
      if (e.shiftKey) {
        return;
      }

      var target = e.target;

      var isArrowLeft = (0, _identifiers.isKeyArrowLeft)(e);
      var isArrowRight = (0, _identifiers.isKeyArrowRight)(e);

      if (
      (0, _isInstanceOf.isInstanceOf)(target, _globalObject.globalObject.Element) && (
      IGNORE_EVENT_TAGS.includes(target.tagName.toLowerCase()) || target.isContentEditable))
      {
        return;
      }

      if (NavigationHelper.checkKeyPressed(e, _this.theme) && isArrowLeft) {
        _this.setState({ focusedItem: null }, _this.goBackward);
        return;
      }
      if (NavigationHelper.checkKeyPressed(e, _this.theme) && isArrowRight) {
        _this.setState({ focusedItem: null }, _this.goForward);
        return;
      }

      if (_this.container && _this.container === e.target) {
        if (isArrowLeft) {
          _this.setState({ focusedByTab: true }, _this.moveFocusLeft);
          return;
        }
        if (isArrowRight) {
          _this.setState({ focusedByTab: true }, _this.moveFocusRight);
          return;
        }
        if ((0, _identifiers.isKeyEnter)(e)) {
          _this.executeItemAction(_this.getFocusedItem());
          return;
        }
      }
    };_this.

    handleFocus = function () {
      if (_this.props.disabled) {
        return;
      }

      _this.setState({ keyboardControl: true });

      // focus event fires before keyDown eventlistener
      // so we should check tabPressed in async way
      _globalObject.globalObject.requestAnimationFrame == null || _globalObject.globalObject.requestAnimationFrame(function () {
        if (_keyListener.keyListener.isTabPressed) {
          _this.setState({ focusedByTab: true });
        }
      });
    };_this.

    handleBlur = function () {
      _this.setState({
        focusedByTab: false,
        keyboardControl: _this.getProps().useGlobalListener || false
      });
    };_this.

    getItems = function () {
      return (0, _PagingHelper.getItems)(_this.props.activePage, _this.props.pagesCount, _this.isMobile).concat('forward');
    };_this.

    getFocusedItem = function () {
      if (!_this.state.focusedByTab) {
        return null;
      }

      var focusedItem = _this.state.focusedItem;
      if (focusedItem && _this.getItems().includes(focusedItem) && _this.isItemFocusable(focusedItem)) {
        return focusedItem;
      }

      return _this.props.activePage;
    };_this.

    isItemFocusable = function (item) {
      return !_this.isItemDisabled(item);
    };_this.

    isItemDisabled = function (item) {
      switch (item) {
        case '.':
          return true;
        case 'forward':
          return !_this.canGoForward();
        default:
          return false;
      }
    };_this.

    executeItemAction = function (item) {
      if (item === 'forward') {
        _this.goForward();
      }
      if (typeof item === 'number') {
        _this.goToPage(item);
      }
    };_this.

    moveFocusLeft = function () {
      _this.moveFocus(-1);
    };_this.

    moveFocusRight = function () {
      _this.moveFocus(1);
    };_this.

    moveFocus = function (step) {
      var focusedItem = _this.getFocusedItem();
      var items = _this.getItems();
      var index = items.findIndex(function (x) {return x === focusedItem;});
      do {
        index = (index + step + items.length) % items.length;
      } while (!_this.isItemFocusable(items[index]));
      _this.setState({ focusedItem: items[index] });
    };_this.

    canGoBackward = function () {
      return _this.props.activePage > 1;
    };_this.

    canGoForward = function () {
      return _this.props.activePage < _this.props.pagesCount;
    };_this.

    goBackward = function () {
      _this.goToPage(_this.props.activePage - 1);
    };_this.

    goForward = function () {
      _this.goToPage(_this.props.activePage + 1);
    };_this.

    goToPage = function (pageNumber) {
      if (pageNumber >= 1 && pageNumber !== _this.props.activePage && pageNumber <= _this.props.pagesCount) {
        _this.props.onPageChange(pageNumber);
      }
    };_this.

    addGlobalListener = function () {var _globalObject$documen;
      if (_this.addedGlobalListener) {
        return;
      }

      (_globalObject$documen = _globalObject.globalObject.document) == null || _globalObject$documen.addEventListener('keydown', _this.handleKeyDown);
      _this.addedGlobalListener = true;
    };_this.

    removeGlobalListener = function () {
      if (_this.addedGlobalListener) {var _globalObject$documen2;
        (_globalObject$documen2 = _globalObject.globalObject.document) == null || _globalObject$documen2.removeEventListener('keydown', _this.handleKeyDown);

        _this.addedGlobalListener = false;
      }
    };_this.

    refContainer = function (element) {
      _this.container = element;
    };_this.

    getPagingSizeClassNames = function () {
      var size = _this.getSize();
      switch (size) {
        case 'legacy':
          return {
            root: _Paging2.styles.pagingLegacy(_this.theme),
            dots: _Paging2.styles.dotsLegacy(_this.theme),
            forwardLink: _Paging2.styles.forwardLinkLegacy(_this.theme),
            pageLink: _Paging2.styles.pageLinkLegacy(_this.theme)
          };
        case 'small':
          return {
            root: _Paging2.styles.pagingSmall(_this.theme),
            dots: _Paging2.styles.dotsSmall(_this.theme),
            forwardLink: _Paging2.styles.forwardLinkSmall(_this.theme),
            pageLink: _Paging2.styles.pageLinkSmall(_this.theme)
          };
        case 'medium':
          return {
            root: _Paging2.styles.pagingMedium(_this.theme),
            dots: _Paging2.styles.dotsMedium(_this.theme),
            forwardLink: _this.isMobile ?
            _Paging2.styles.forwardLinkMediumMobile(_this.theme) :
            _Paging2.styles.forwardLinkMedium(_this.theme),
            pageLink: _Paging2.styles.pageLinkMedium(_this.theme)
          };
        case 'large':
          return {
            root: _Paging2.styles.pagingLarge(_this.theme),
            dots: _Paging2.styles.dotsLarge(_this.theme),
            forwardLink: _this.isMobile ? _Paging2.styles.forwardLinkLargeMobile(_this.theme) : _Paging2.styles.forwardLinkLarge(_this.theme),
            pageLink: _Paging2.styles.pageLinkLarge(_this.theme)
          };
        default:
          throw new TypeError("Invalid size prop: '" + _this.props.size + "'");
      }
    };_this.

    getDotsIcon = function () {
      var size = _this.getSize();
      return size === 'legacy' ? '...' : /*#__PURE__*/_react.default.createElement(_DotsIcon.DotsIcon, { size: size });
    };_this.

    getForwardIcon = function () {
      var size = _this.getSize();
      var iconSize = size === 'legacy' ? parseInt(_this.theme.pagingForwardIconSize) : size;
      return _this.isMobile ? /*#__PURE__*/
      _react.default.createElement(_ForwardIcon.ForwardIconMobile, { size: iconSize }) : /*#__PURE__*/

      _react.default.createElement(_ForwardIcon.ForwardIcon, { size: iconSize, style: { marginLeft: 4 } });

    };_this.

    getSize = function () {
      if (_this.props.size) {
        return _this.isMobile && _this.props.size === 'small' ? 'medium' : _this.props.size;
      }

      var defaultSize = (0, _ThemeHelpers.isThemeGTE)(_this.theme, '5.3') ? 'small' : 'legacy';
      return _this.isMobile && defaultSize === 'small' ? 'medium' : defaultSize;
    };return _this;}(0, _inheritsLoose2.default)(Paging, _React$PureComponent);Paging.isForward = function isForward(pageNumber) {return pageNumber === 'forward';};var _proto = Paging.prototype;_proto.componentDidMount = function componentDidMount() {var useGlobalListener = this.getProps().useGlobalListener;if (useGlobalListener) {this.addGlobalListener();}};_proto.componentDidUpdate = function componentDidUpdate(prevProps) {var useGlobalListener = this.getProps().useGlobalListener;if (!prevProps.useGlobalListener && useGlobalListener) {this.addGlobalListener();}if (prevProps.useGlobalListener && !useGlobalListener) {this.removeGlobalListener();}if (prevProps.useGlobalListener !== useGlobalListener) {this.setState({ keyboardControl: useGlobalListener });}};_proto.componentWillUnmount = function componentWillUnmount() {this.removeGlobalListener();};_proto.render = function render() {var _this2 = this;if (this.props.pagesCount < 2) {return null;}return /*#__PURE__*/_react.default.createElement(_ThemeContext.ThemeContext.Consumer, null, function (theme) {_this2.theme = theme;return /*#__PURE__*/_react.default.createElement(_ResponsiveLayout.ResponsiveLayout, null, function (_ref) {var isMobile = _ref.isMobile;_this2.isMobile = isMobile && (0, _ThemeHelpers.isThemeGTE)(_this2.theme, '5.3');_this2.sizeClassNames = _this2.getPagingSizeClassNames();return _this2.renderMain();});});};_proto.renderMain = function renderMain() {var _cx4,_this3 = this;var _this$getProps = this.getProps(),useGlobalListener = _this$getProps.useGlobalListener;return /*#__PURE__*/_react.default.createElement(_CommonWrapper.CommonWrapper, (0, _extends2.default)({ rootNodeRef: this.setRootNode }, this.props, (0, _getVisualStateDataAttributes.getVisualStateDataAttributes)({ disabled: this.props.disabled })), /*#__PURE__*/_react.default.createElement("span", { tabIndex: this.props.disabled ? -1 : 0, "data-tid": PagingDataTids.root, className: (0, _Emotion.cx)(_Paging2.styles.paging(), this.sizeClassNames.root, (_cx4 = {}, _cx4[_Paging2.styles.pagingMobile()] = this.isMobile, _cx4[_Paging2.styles.pagingDisabled()] = this.props.disabled, _cx4)), onKeyDown: useGlobalListener ? undefined : this.handleKeyDown, onFocus: this.handleFocus, onBlur: this.handleBlur, onMouseDown: this.handleMouseDown, ref: this.refContainer }, this.getItems().map(function (item, index) {return _this3.renderItem(item, index);})));};return Paging;}(_react.default.PureComponent), _Paging.__KONTUR_REACT_UI__ = 'Paging', _Paging.displayName = 'Paging', _Paging.defaultProps = { component: _PagingDefaultComponent.PagingDefaultComponent, useGlobalListener: false }, _Paging)) || _class) || _class);