"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 = exports.RATING_SIZE = void 0;

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

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

var _Star = _interopRequireDefault(require("./subcomponents/Star"));

var _RateCounter = _interopRequireDefault(require("./subcomponents/RateCounter"));

var _utils = require("../utils");

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

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 RATING_SIZE = {
  XS: 'xs',
  S: 's'
};
exports.RATING_SIZE = RATING_SIZE;

var generateArrayRange = function generateArrayRange(range) {
  var array = Array(range);

  for (var i = 0; i < range; i++) {
    array[i] = i;
  }

  return array;
};

function generateName() {
  return "rating".concat(Math.random().toString(36).substring(7));
}

/* eslint-disable react/default-props-match-prop-types */
// legacy files without proper flow checks can suffer from this
var Rating = /*#__PURE__*/function (_React$Component) {
  _inherits(Rating, _React$Component);

  var _super = _createSuper(Rating);

  function Rating(props) {
    var _this;

    _classCallCheck(this, Rating);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "name", void 0);

    _defineProperty(_assertThisInitialized(_this), "starsOnChangeFunctions", []);

    _defineProperty(_assertThisInitialized(_this), "starsMouseEnterFunctions", []);

    _defineProperty(_assertThisInitialized(_this), "onStarChange", function (index) {
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          _this$props$active = _this$props.active,
          active = _this$props$active === void 0 ? false : _this$props$active;

      if (!active) {
        return;
      }

      var ratedStarIndex = index + 1;
      onChange(ratedStarIndex);
    });

    _defineProperty(_assertThisInitialized(_this), "onStarMouseEnter", function (index, event) {
      var _this$props2 = _this.props,
          onStarMouseEnter = _this$props2.onStarMouseEnter,
          _this$props2$active = _this$props2.active,
          active = _this$props2$active === void 0 ? false : _this$props2$active;

      if (!active) {
        return;
      }

      onStarMouseEnter(index + 1, event);
    });

    _defineProperty(_assertThisInitialized(_this), "onMouseLeave", function () {
      _this.props.onMouseLeave();
    });

    _this.createStarsOnChangeFunctions(_this.props.metricSize);

    _this.createStarsMouseEnterFunctions(_this.props.metricSize);

    _this.name = generateName();
    return _this;
  }

  _createClass(Rating, [{
    key: "componentWillReciveProps",
    value: function componentWillReciveProps(nextProps) {
      if (this.props.metricSize !== nextProps.metricSize) {
        this.createStarsOnChangeFunctions(nextProps.metricSize);
        this.createStarsMouseEnterFunctions(this.props.metricSize);
      }
    }
  }, {
    key: "createStarsOnChangeFunctions",
    value: function createStarsOnChangeFunctions(metricSize) {
      var _this2 = this;

      this.starsOnChangeFunctions = generateArrayRange(metricSize).map(function (rangeIndex) {
        return function () {
          return _this2.onStarChange(rangeIndex);
        };
      });
    }
  }, {
    key: "createStarsMouseEnterFunctions",
    value: function createStarsMouseEnterFunctions(metricSize) {
      var _this3 = this;

      this.starsMouseEnterFunctions = generateArrayRange(metricSize).map(function (rangeIndex) {
        return function (event) {
          return _this3.onStarMouseEnter(rangeIndex, event);
        };
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props3 = this.props,
          metricSize = _this$props3.metricSize,
          rate = _this$props3.rate,
          _this$props3$size = _this$props3.size,
          size = _this$props3$size === void 0 ? RATING_SIZE.XS : _this$props3$size,
          active = _this$props3.active,
          className = _this$props3.className,
          counterText = _this$props3.counterText,
          activeText = _this$props3.activeText,
          label = _this$props3['aria-label'],
          _this$props3$noLabel = _this$props3.noLabel,
          noLabel = _this$props3$noLabel === void 0 ? false : _this$props3$noLabel;
      var ratingClass = (0, _classnames.default)('sg-rate-box', {
        'sg-rate-box--s': size === RATING_SIZE.S,
        'sg-rate-box--active': active
      }, className);
      var starsProps = generateArrayRange(metricSize).map(function (rangeIndex) {
        return {
          size: size === 's' ? 32 : 24,
          onChange: _this4.starsOnChangeFunctions[rangeIndex],
          active: active,
          name: _this4.name,
          'aria-label': "".concat(rangeIndex + 1, "/").concat(metricSize),
          value: rangeIndex + 1
        };
      });
      var rateString = rate.toLocaleString(undefined, {
        minimumFractionDigits: 1,
        maximumFractionDigits: 1
      });
      var rateLabel = "".concat(activeText || '', ", min: 1, max: ").concat(metricSize);
      var metricString = "".concat(rate, "/").concat(metricSize);

      if (_utils.__DEV__) {
        (0, _utils.invariant)(!(active && !this.props.onChange), // eslint-disable-next-line max-len
        'You provided an `active` prop to a Rating without an `onChange` handler. Users won`t be able to rate.');
        (0, _utils.invariant)(!(!active && this.props.onChange), // eslint-disable-next-line max-len
        'You provided an `onChange` handler to a Rating without an `active` prop. Users won`t be able to rate.');
      }

      return /*#__PURE__*/React.createElement("div", {
        className: ratingClass
      }, /*#__PURE__*/React.createElement("span", {
        className: "sg-visually-hidden"
      }, label), /*#__PURE__*/React.createElement("p", {
        className: "sg-rate-box__rate"
      }, !noLabel && /*#__PURE__*/React.createElement("span", {
        "aria-hidden": true
      }, rateString), Boolean(rate) && /*#__PURE__*/React.createElement("span", {
        className: "sg-visually-hidden"
      }, metricString)), /*#__PURE__*/React.createElement("div", {
        className: "sg-rate-box__stars-container",
        onMouseLeave: this.onMouseLeave
      }, /*#__PURE__*/React.createElement("div", {
        className: "sg-rate-box__filled-stars",
        style: {
          width: "".concat(100 * rate / metricSize, "%")
        },
        "aria-hidden": true
      }, starsProps.map(function (props) {
        return /*#__PURE__*/React.createElement(_Star.default, {
          key: props.value,
          size: props.size
        });
      })), /*#__PURE__*/React.createElement("div", {
        className: "sg-rate-box__background-stars",
        role: "radiogroup",
        "aria-hidden": !active,
        "aria-label": rateLabel
      }, starsProps.map(function (props) {
        return /*#__PURE__*/React.createElement(_Star.default, _extends({
          key: props.value,
          onMouseEnter: _this4.starsMouseEnterFunctions[props.value]
        }, props, {
          type: "star_outlined"
        }));
      }))), /*#__PURE__*/React.createElement(_RateCounter.default, {
        activeText: activeText,
        counterText: counterText
      }));
    }
  }]);

  return Rating;
}(React.Component);

_defineProperty(Rating, "defaultProps", {
  onChange: function onChange() {
    return undefined;
  },
  onStarMouseEnter: function onStarMouseEnter() {
    return undefined;
  },
  onMouseLeave: function onMouseLeave() {
    return undefined;
  },
  metricSize: 5,
  rate: 0,
  'aria-label': 'current rate'
});

var _default = Rating;
exports.default = _default;