"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.isWidthDown = exports.isWidthUp = 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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

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

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

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

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

var _reactEventListener = _interopRequireDefault(require("react-event-listener"));

var _debounce = _interopRequireDefault(require("debounce"));

var _utils = require("@material-ui/utils");

var _styles = require("@material-ui/styles");

var _hoistNonReactStatics = _interopRequireDefault(require("hoist-non-react-statics"));

var _withTheme = _interopRequireDefault(require("../styles/withTheme"));

var _createBreakpoints = require("../styles/createBreakpoints");

// < 1kb payload overhead when lodash/debounce is > 3kb.
// By default, returns true if screen width is the same or greater than the given breakpoint.
var isWidthUp = function isWidthUp(breakpoint, width) {
  var inclusive = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  if (inclusive) {
    return _createBreakpoints.keys.indexOf(breakpoint) <= _createBreakpoints.keys.indexOf(width);
  }

  return _createBreakpoints.keys.indexOf(breakpoint) < _createBreakpoints.keys.indexOf(width);
}; // By default, returns true if screen width is the same or less than the given breakpoint.


exports.isWidthUp = isWidthUp;

var isWidthDown = function isWidthDown(breakpoint, width) {
  var inclusive = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  if (inclusive) {
    return _createBreakpoints.keys.indexOf(width) <= _createBreakpoints.keys.indexOf(breakpoint);
  }

  return _createBreakpoints.keys.indexOf(width) < _createBreakpoints.keys.indexOf(breakpoint);
};

exports.isWidthDown = isWidthDown;

var withWidth = function withWidth() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (Component) {
    var _options$withTheme = options.withTheme,
        withThemeOption = _options$withTheme === void 0 ? false : _options$withTheme,
        _options$noSSR = options.noSSR,
        noSSR = _options$noSSR === void 0 ? false : _options$noSSR,
        initialWidthOption = options.initialWidth,
        _options$resizeInterv = options.resizeInterval,
        resizeInterval = _options$resizeInterv === void 0 ? 166 : _options$resizeInterv;

    var WithWidth =
    /*#__PURE__*/
    function (_React$Component) {
      (0, _inherits2.default)(WithWidth, _React$Component);

      function WithWidth(props) {
        var _this;

        (0, _classCallCheck2.default)(this, WithWidth);
        _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(WithWidth).call(this, props));
        _this.state = {
          width: noSSR ? _this.getWidth() : undefined
        };

        if (typeof window !== 'undefined') {
          _this.handleResize = (0, _debounce.default)(function () {
            var width2 = _this.getWidth();

            if (width2 !== _this.state.width) {
              _this.setState({
                width: width2
              });
            }
          }, resizeInterval);
        }

        return _this;
      }

      (0, _createClass2.default)(WithWidth, [{
        key: "componentDidMount",
        value: function componentDidMount() {
          var width = this.getWidth();

          if (width !== this.state.width) {
            this.setState({
              width: width
            });
          }
        }
      }, {
        key: "componentWillUnmount",
        value: function componentWillUnmount() {
          this.handleResize.clear();
        }
      }, {
        key: "getWidth",
        value: function getWidth() {
          var innerWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.innerWidth;
          var breakpoints = this.props.theme.breakpoints;
          var width = null;
          /**
           * Start with the slowest value as low end devices often have a small screen.
           *
           * innerWidth |xs      sm      md      lg      xl
           *            |-------|-------|-------|-------|------>
           * width      |  xs   |  sm   |  md   |  lg   |  xl
           */

          var index = 1;

          while (width === null && index < _createBreakpoints.keys.length) {
            var currentWidth = _createBreakpoints.keys[index]; // @media are inclusive, so reproduce the behavior here.

            if (innerWidth < breakpoints.values[currentWidth]) {
              width = _createBreakpoints.keys[index - 1];
              break;
            }

            index += 1;
          }

          width = width || 'xl';
          return width;
        }
      }, {
        key: "render",
        value: function render() {
          var _getThemeProps = (0, _styles.getThemeProps)({
            theme: this.props.theme,
            name: 'MuiWithWidth',
            props: (0, _extends2.default)({}, this.props)
          }),
              initialWidth = _getThemeProps.initialWidth,
              theme = _getThemeProps.theme,
              width = _getThemeProps.width,
              other = (0, _objectWithoutProperties2.default)(_getThemeProps, ["initialWidth", "theme", "width"]);

          var more = (0, _extends2.default)({
            width: width || this.state.width || initialWidth || initialWidthOption
          }, other); // When rendering the component on the server,
          // we have no idea about the client browser screen width.
          // In order to prevent blinks and help the reconciliation of the React tree
          // we are not rendering the child component.
          //
          // An alternative is to use the `initialWidth` property.

          if (more.width === undefined) {
            return null;
          }

          if (withThemeOption) {
            more.theme = theme;
          }

          return _react.default.createElement(_react.default.Fragment, null, _react.default.createElement(Component, more), _react.default.createElement(_reactEventListener.default, {
            target: "window",
            onResize: this.handleResize
          }));
        }
      }]);
      return WithWidth;
    }(_react.default.Component);

    process.env.NODE_ENV !== "production" ? WithWidth.propTypes = {
      /**
       * As `window.innerWidth` is unavailable on the server,
       * we default to rendering an empty component during the first mount.
       * You might want to use an heuristic to approximate
       * the screen width of the client browser screen width.
       *
       * For instance, you could be using the user-agent or the client-hints.
       * https://caniuse.com/#search=client%20hint
       */
      initialWidth: _propTypes.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl']),

      /**
       * @ignore
       */
      theme: _propTypes.default.object.isRequired,

      /**
       * Bypass the width calculation logic.
       */
      width: _propTypes.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl'])
    } : void 0;

    if (process.env.NODE_ENV !== 'production') {
      WithWidth.displayName = "WithWidth(".concat((0, _utils.getDisplayName)(Component), ")");
    }

    (0, _hoistNonReactStatics.default)(WithWidth, Component);
    return (0, _withTheme.default)(WithWidth);
  };
};

var _default = withWidth;
exports.default = _default;