"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

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

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

var _easyBem = _interopRequireDefault(require("easy-bem"));

require("./style.css");

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

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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; }

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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); 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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

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

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; } }

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

var cn = (0, _easyBem["default"])('indiana-scroll-container');
var SCROLL_END_DEBOUNCE = 300;
var LEFT_BUTTON = 0;

var ScrollContainer = /*#__PURE__*/function (_PureComponent) {
  _inherits(ScrollContainer, _PureComponent);

  var _super = _createSuper(ScrollContainer);

  function ScrollContainer(props) {
    var _this;

    _classCallCheck(this, ScrollContainer);

    _this = _super.call(this, props);

    _this.onEndScroll = function (e) {
      var _e$target = e.target,
          clientHeight = _e$target.clientHeight,
          scrollHeight = _e$target.scrollHeight,
          scrollTop = _e$target.scrollTop;
      if (clientHeight + scrollTop >= scrollHeight - 50) _this.props.onScrollBottom(e);
      _this.scrolling = false;

      if (!_this.pressed && _this.started) {
        _this.processEnd(e);
      }
    };

    _this.onScroll = function (e) {
      var _e$target2 = e.target,
          clientHeight = _e$target2.clientHeight,
          scrollHeight = _e$target2.scrollHeight,
          scrollTop = _e$target2.scrollTop;
      var container = _this.container.current; // Ignore the internal scrolls

      if (container.scrollLeft !== _this.scrollLeft || container.scrollTop !== _this.scrollTop) {
        _this.scrolling = true;

        _this.processScroll(e);

        _this.onEndScroll({
          target: {
            clientHeight: clientHeight,
            scrollHeight: scrollHeight,
            scrollTop: scrollTop
          }
        });
      }
    };

    _this.onTouchStart = function (e) {
      var nativeMobileScroll = _this.props.nativeMobileScroll;

      if (_this.isDraggable(e.target)) {
        _this.internal = true;

        if (nativeMobileScroll && _this.scrolling) {
          _this.pressed = true;
        } else {
          var touch = e.touches[0];

          _this.processClick(e, touch.clientX, touch.clientY);

          if (!nativeMobileScroll && _this.props.stopPropagation) {
            e.stopPropagation();
          }
        }
      }
    };

    _this.onTouchEnd = function (e) {
      var nativeMobileScroll = _this.props.nativeMobileScroll;

      if (_this.pressed) {
        if (_this.started && (!_this.scrolling || !nativeMobileScroll)) {
          _this.processEnd();
        } else {
          _this.pressed = false;
        }

        _this.forceUpdate();
      }
    };

    _this.onTouchMove = function (e) {
      var nativeMobileScroll = _this.props.nativeMobileScroll;

      if (_this.pressed && (!nativeMobileScroll || !_this.isMobile)) {
        var touch = e.touches[0];

        if (touch) {
          _this.processMove(e, touch.clientX, touch.clientY);
        } // e.preventDefault(); // 处理无法拖动选中文字的问题，先屏蔽禁止默认事件


        if (_this.props.stopPropagation) {
          e.stopPropagation();
        }
      }
    };

    _this.onMouseDown = function (e) {
      if (_this.isDraggable(e.target) && _this.isScrollable()) {
        _this.internal = true;

        if (_this.props.buttons.indexOf(e.button) !== -1) {
          _this.processClick(e, e.clientX, e.clientY); // e.preventDefault();


          if (_this.props.stopPropagation) {
            e.stopPropagation();
          }
        }
      }
    };

    _this.onMouseMove = function (e) {
      if (_this.pressed) {
        _this.processMove(e, e.clientX, e.clientY); // e.preventDefault();


        if (_this.props.stopPropagation) {
          e.stopPropagation();
        }
      }
    };

    _this.onMouseUp = function (e) {
      if (_this.pressed) {
        if (_this.started) {
          _this.processEnd();
        } else {
          _this.internal = false;
          _this.pressed = false;

          _this.forceUpdate();

          if (_this.props.onClick) {
            _this.props.onClick(e);
          }
        } // e.preventDefault();


        if (_this.props.stopPropagation) {
          e.stopPropagation();
        }
      }
    };

    _this.container = /*#__PURE__*/_react["default"].createRef();
    _this.onEndScroll = (0, _lodash["default"])(_this.onEndScroll, SCROLL_END_DEBOUNCE); // Is container scrolling now (for example by inertia)

    _this.scrolling = false; // Is scrolling started

    _this.started = false; // Is touch active or mouse pressed down

    _this.pressed = false; // Is event internal

    _this.internal = false; // Bind callbacks

    _this.getRef = _this.getRef.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(ScrollContainer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var nativeMobileScroll = this.props.nativeMobileScroll;
      var container = this.container.current;
      window.addEventListener('mouseup', this.onMouseUp, {
        capture: true
      });
      window.addEventListener('mousemove', this.onMouseMove, {
        capture: true
      });
      window.addEventListener('touchmove', this.onTouchMove, {
        passive: false,
        capture: true
      });
      window.addEventListener('touchend', this.onTouchEnd, {
        capture: true
      }); // due to https://github.com/facebook/react/issues/9809#issuecomment-414072263

      container.addEventListener('touchstart', this.onTouchStart, {
        passive: false
      });
      container.addEventListener('mousedown', this.onMouseDown, {
        passive: false
      });

      if (nativeMobileScroll) {
        // We should check if it's the mobile device after page was loaded
        // to prevent breaking SSR
        this.isMobile = this.isMobileDevice(); // If it's the mobile device, we should rerender to change styles

        if (this.isMobile) {
          this.forceUpdate();
        }
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      window.removeEventListener('mouseup', this.onMouseUp);
      window.removeEventListener('mousemove', this.onMouseMove);
      window.removeEventListener('touchmove', this.onTouchMove);
      window.removeEventListener('touchend', this.onTouchEnd);
    }
  }, {
    key: "getElement",
    value: function getElement() {
      return this.container.current;
    }
  }, {
    key: "isMobileDevice",
    value: function isMobileDevice() {
      return typeof window.orientation !== 'undefined' || navigator.userAgent.indexOf('IEMobile') !== -1;
    }
  }, {
    key: "isDraggable",
    value: function isDraggable(target) {
      var ignoreElements = this.props.ignoreElements;

      if (ignoreElements) {
        var closest = target.closest(ignoreElements);
        return closest === null || closest.contains(this.getElement());
      }

      return true;
    }
  }, {
    key: "isScrollable",
    value: function isScrollable() {
      var container = this.container.current;
      return container && (container.scrollWidth > container.clientWidth || container.scrollHeight > container.clientHeight);
    } // Simulate 'onEndScroll' event that fires when scrolling is stopped

  }, {
    key: "processClick",
    value: function processClick(e, clientX, clientY) {
      var container = this.container.current;
      this.scrollLeft = container.scrollLeft;
      this.scrollTop = container.scrollTop;
      this.clientX = clientX;
      this.clientY = clientY;
      this.pressed = true;
    }
  }, {
    key: "processStart",
    value: function processStart() {
      var changeCursor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var onStartScroll = this.props.onStartScroll;
      this.started = true; // Add the class to change displayed cursor

      if (changeCursor) {
        document.body.classList.add('indiana-dragging');
      }

      if (onStartScroll) {
        onStartScroll({
          external: !this.internal
        });
      }

      this.forceUpdate();
    } // Process native scroll (scrollbar, mobile scroll)

  }, {
    key: "processScroll",
    value: function processScroll(e) {
      if (this.started) {
        var onScroll = this.props.onScroll;

        if (onScroll) {
          onScroll({
            external: !this.internal
          });
        }
      } else {
        this.processStart(false);
      }
    } // Process non-native scroll

  }, {
    key: "processMove",
    value: function processMove(e, newClientX, newClientY) {
      var _this$props = this.props,
          horizontal = _this$props.horizontal,
          vertical = _this$props.vertical,
          activationDistance = _this$props.activationDistance,
          onScroll = _this$props.onScroll;
      var container = this.container.current;

      if (!this.started) {
        if (horizontal && Math.abs(newClientX - this.clientX) > activationDistance || vertical && Math.abs(newClientY - this.clientY) > activationDistance) {
          this.clientX = newClientX;
          this.clientY = newClientY;
          this.processStart();
        }
      } else {
        if (horizontal) {
          container.scrollLeft -= newClientX - this.clientX;
        }

        if (vertical) {
          container.scrollTop -= newClientY - this.clientY;
        }

        if (onScroll) {
          onScroll({
            external: !this.internal
          });
        }

        this.clientX = newClientX;
        this.clientY = newClientY;
        this.scrollLeft = container.scrollLeft;
        this.scrollTop = container.scrollTop;
      }
    }
  }, {
    key: "processEnd",
    value: function processEnd(e) {
      var onEndScroll = this.props.onEndScroll;
      var container = this.container.current;

      if (container && onEndScroll) {
        onEndScroll(_objectSpread(_objectSpread({}, e), {}, {
          external: !this.internal
        }));
      }

      this.pressed = false;
      this.started = false;
      this.scrolling = false;
      this.internal = false;
      document.body.classList.remove('indiana-dragging');
      this.forceUpdate();
    }
  }, {
    key: "getRef",
    value: function getRef(el) {
      ;
      [this.container, this.props.innerRef].forEach(function (ref) {
        if (ref) {
          if (typeof ref === 'function') {
            ref(el);
          } else {
            ;
            ref.current = el;
          }
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          children = _this$props2.children,
          draggingClassName = _this$props2.draggingClassName,
          className = _this$props2.className,
          style = _this$props2.style,
          hideScrollbars = _this$props2.hideScrollbars,
          Component = _this$props2.component;
      return /*#__PURE__*/_react["default"].createElement(Component, {
        className: (0, _classnames["default"])(className, this.pressed && draggingClassName, cn({
          dragging: this.pressed,
          'hide-scrollbars': hideScrollbars,
          'native-scroll': this.isMobile
        })),
        style: style,
        ref: this.getRef,
        onScroll: this.onScroll
      }, children);
    }
  }]);

  return ScrollContainer;
}(_react.PureComponent);

exports["default"] = ScrollContainer;
ScrollContainer.defaultProps = {
  nativeMobileScroll: true,
  hideScrollbars: true,
  activationDistance: 10,
  vertical: true,
  horizontal: true,
  stopPropagation: false,
  style: {},
  component: 'div',
  buttons: [LEFT_BUTTON]
};