"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

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 _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

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

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

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

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

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

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

var _reactSelect = _interopRequireDefault(require("react-select"));

var _creatable = _interopRequireDefault(require("react-select/creatable"));

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

var _uiIcons = require("@teamleader/ui-icons");

var _box = _interopRequireWildcard(require("../box"));

var _icon = _interopRequireDefault(require("../icon"));

var _validationText = _interopRequireDefault(require("../validationText"));

var _constants = require("../../constants");

var _theme = _interopRequireDefault(require("./theme.css"));

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

var _uiUtilities = _interopRequireDefault(require("@teamleader/ui-utilities"));

var _excluded = ["components", "creatable", "error", "inverse", "helpText", "size", "success", "warning", "forwardedRef"];

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) { (0, _defineProperty2.default)(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

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

var minHeightBySizeMap = {
  tiny: 24,
  small: 30,
  medium: 36,
  large: 48
};

var DropdownIndicator = function DropdownIndicator(_ref) {
  var inverse = _ref.selectProps.inverse;
  return /*#__PURE__*/_react.default.createElement(_icon.default, {
    alignItems: "center",
    className: _theme.default['dropdown-indicator'],
    color: inverse ? 'teal' : 'neutral',
    display: "flex",
    justifyContent: "center",
    tint: inverse ? 'lightest' : 'darkest'
  }, /*#__PURE__*/_react.default.createElement(_uiIcons.IconChevronDownSmallOutline, null));
};

var ClearIndicator = function ClearIndicator(_ref2) {
  var innerProps = _ref2.innerProps,
      inverse = _ref2.selectProps.inverse;
  return /*#__PURE__*/_react.default.createElement(_icon.default, (0, _extends2.default)({
    color: inverse ? 'teal' : 'neutral',
    display: "flex",
    tint: inverse ? 'lightest' : 'darkest'
  }, innerProps), /*#__PURE__*/_react.default.createElement(_uiIcons.IconCloseBadgedSmallFilled, null));
};

var selectOverlayNode = document.createElement('div');
exports.selectOverlayNode = selectOverlayNode;
selectOverlayNode.setAttribute('data-teamleader-ui', 'select-overlay');
var activeSelects = new Set();

var Select = /*#__PURE__*/function (_PureComponent) {
  (0, _inherits2.default)(Select, _PureComponent);

  var _super = _createSuper(Select);

  function Select() {
    var _this;

    (0, _classCallCheck2.default)(this, Select);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getClearIndicatorStyles", function (base) {
      var inverse = _this.props.inverse;
      return _objectSpread(_objectSpread({}, base), {}, {
        color: inverse ? _constants.COLOR.TEAL.LIGHTEST : _constants.COLOR.TEAL.DARK,
        '&:hover': {
          color: inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST
        },
        cursor: 'pointer',
        svg: {
          height: '14px',
          width: '14px'
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getControlStyles", function (base, _ref3) {
      var isDisabled = _ref3.isDisabled,
          isFocused = _ref3.isFocused;
      var _this$props = _this.props,
          error = _this$props.error,
          inverse = _this$props.inverse,
          size = _this$props.size,
          success = _this$props.success,
          warning = _this$props.warning,
          width = _this$props.width;

      var commonStyles = _objectSpread(_objectSpread({}, base), {}, {
        minHeight: minHeightBySizeMap[size],
        width: width
      });

      if (inverse) {
        return _objectSpread(_objectSpread({}, commonStyles), {}, {
          backgroundColor: isDisabled ? _constants.COLOR.TEAL.DARK : _constants.COLOR.TEAL.NORMAL,
          '&:hover': {
            borderColor: !error && !warning && !success && _constants.COLOR.TEAL.LIGHT
          },
          borderColor: error ? _constants.COLOR.RUBY.LIGHT : warning ? _constants.COLOR.GOLD.LIGHT : success ? _constants.COLOR.MINT.LIGHT : isDisabled ? _constants.COLOR.TEAL.DARK : isFocused ? _constants.COLOR.TEAL.LIGHT : _constants.COLOR.TEAL.NORMAL,
          boxShadow: error ? "0 0 0 1px ".concat(_constants.COLOR.RUBY.LIGHT) : warning ? "0 0 0 1px ".concat(_constants.COLOR.GOLD.LIGHT) : success ? "0 0 0 1px ".concat(_constants.COLOR.MINT.LIGHT) : isFocused ? "0 0 0 1px ".concat(_constants.COLOR.TEAL.LIGHT) : 'none'
        });
      }

      return _objectSpread(_objectSpread({}, commonStyles), {}, {
        backgroundColor: isDisabled ? _constants.COLOR.NEUTRAL.NORMAL : _constants.COLOR.NEUTRAL.LIGHTEST,
        '&:hover': {
          borderColor: !error && !warning && !success && _constants.COLOR.NEUTRAL.DARKEST
        },
        borderColor: error ? _constants.COLOR.RUBY.DARK : warning ? _constants.COLOR.GOLD.DARK : success ? _constants.COLOR.MINT.DARK : isDisabled ? _constants.COLOR.NEUTRAL.NORMAL : isFocused ? _constants.COLOR.NEUTRAL.DARKEST : _constants.COLOR.NEUTRAL.DARK,
        boxShadow: error ? "0 0 0 1px ".concat(_constants.COLOR.RUBY.DARK) : warning ? "0 0 0 1px ".concat(_constants.COLOR.GOLD.DARK) : success ? "0 0 0 1px ".concat(_constants.COLOR.MINT.DARK) : isFocused ? "0 0 0 1px ".concat(_constants.COLOR.NEUTRAL.DARKEST) : 'none'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getGroupStyles", function (base) {
      var inverse = _this.props.inverse;
      return _objectSpread(_objectSpread({}, base), {}, {
        borderBottomColor: inverse ? _constants.COLOR.TEAL.LIGHT : _constants.COLOR.NEUTRAL.NORMAL,
        borderBottomStyle: 'solid',
        borderBottomWidth: '1px',
        '&:last-child': {
          borderWidth: 0
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getGroupHeadingStyles", function (base) {
      var inverse = _this.props.inverse;
      return _objectSpread(_objectSpread({}, base), {}, {
        color: inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST,
        fontSize: '12px',
        fontWeight: '700',
        letterSpacing: '0.6px'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getInput", function (base) {
      return _objectSpread(_objectSpread({}, base), {}, {
        marginLeft: '2px',
        paddingBottom: 0,
        paddingTop: 0
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMenuStyles", function (base) {
      var menuHorizontalOffset = _this.props.menuHorizontalOffset;
      return _objectSpread(_objectSpread({}, base), {}, {
        marginTop: 3,
        marginBottom: 3
      }, menuHorizontalOffset ? {
        right: menuHorizontalOffset,
        position: 'absolute'
      } : {});
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMenuPortalStyles", function (base) {
      var _this$props2 = _this.props,
          inverse = _this$props2.inverse,
          menuWidth = _this$props2.menuWidth;
      return _objectSpread(_objectSpread(_objectSpread({}, base), menuWidth && {
        width: menuWidth
      }), {}, {
        backgroundColor: inverse ? _constants.COLOR.TEAL.NORMAL : _constants.COLOR.NEUTRAL.LIGHTEST,
        fontFamily: 'Inter',
        fontSize: '14px',
        fontWeight: 400,
        fontSmoothing: 'antialiased',
        MozOsxFontSmoothing: 'grayscale',
        WebkitFontSmoothing: 'antialiased',
        zIndex: 500
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMultiValueStyles", function (base) {
      var inverse = _this.props.inverse;
      return _objectSpread(_objectSpread({}, base), {}, {
        borderColor: inverse ? _constants.COLOR.TEAL.DARK : _constants.COLOR.NEUTRAL.NORMAL,
        borderStyle: 'solid',
        borderWidth: '1px',
        borderRadius: '4px',
        margin: '1px'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMultiValueLabelStyles", function (base) {
      var _this$props3 = _this.props,
          inverse = _this$props3.inverse,
          size = _this$props3.size;
      return _objectSpread(_objectSpread({}, base), {}, {
        backgroundColor: inverse ? _constants.COLOR.TEAL.DARK : _constants.COLOR.NEUTRAL.LIGHT,
        borderRadius: 0,
        color: inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST,
        fontFamily: 'Inter',
        fontWeight: 500,
        fontSize: size === 'tiny' || size === 'small' ? '12px' : '14px',
        lineHeight: size === 'tiny' || size === 'small' ? '1' : '18px',
        padding: size === 'tiny' ? '3px' : size === 'large' ? '9px' : '6px'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getMultiValueRemoveStyles", function (base) {
      var _this$props4 = _this.props,
          inverse = _this$props4.inverse,
          size = _this$props4.size;
      return _objectSpread(_objectSpread({}, base), {}, {
        backgroundColor: inverse ? _constants.COLOR.TEAL.DARK : _constants.COLOR.NEUTRAL.LIGHT,
        borderRadius: 0,
        color: inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST,
        '&:hover': {
          backgroundColor: inverse ? _constants.COLOR.TEAL.DARKEST : _constants.COLOR.NEUTRAL.NORMAL,
          color: inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST
        },
        paddingLeft: size === 'tiny' ? '3px' : '6px',
        paddingRight: size === 'tiny' ? '3px' : '6px',
        transition: 'background-color .35s cubic-bezier(.4, 0, .2, 1)'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getOptionStyles", function (base, _ref4) {
      var isDisabled = _ref4.isDisabled,
          isFocused = _ref4.isFocused,
          isSelected = _ref4.isSelected;
      var truncateOptionText = _this.props.truncateOptionText;

      var commonStyles = _objectSpread(_objectSpread(_objectSpread({}, base), truncateOptionText ? {
        overflow: 'hidden',
        textOverflow: 'ellipsis'
      } : {
        wordBreak: 'break-word'
      }), {}, {
        padding: '8px 12px'
      });

      if (_this.props.inverse) {
        return _objectSpread(_objectSpread({}, commonStyles), {}, {
          color: isDisabled ? _constants.COLOR.TEAL.LIGHT : isSelected ? _constants.COLOR.NEUTRAL.LIGHTEST : isFocused ? _constants.COLOR.TEAL.DARK : _constants.COLOR.NEUTRAL.LIGHTEST,
          backgroundColor: isSelected ? _constants.COLOR.TEAL.DARK : isFocused ? _constants.COLOR.TEAL.LIGHT : _constants.COLOR.TEAL.NORMAL,
          '&:active': {
            backgroundColor: isDisabled ? _constants.COLOR.TEAL.NORMAL : _constants.COLOR.TEAL.DARK,
            color: isDisabled ? _constants.COLOR.TEAL.LIGHT : _constants.COLOR.NEUTRAL.LIGHTEST
          }
        });
      }

      return _objectSpread(_objectSpread({}, commonStyles), {}, {
        color: isDisabled ? _constants.COLOR.NEUTRAL.DARK : _constants.COLOR.TEAL.DARK,
        backgroundColor: isSelected ? _constants.COLOR.AQUA.LIGHTEST : isFocused ? _constants.COLOR.NEUTRAL.LIGHT : _constants.COLOR.NEUTRAL.LIGHTEST,
        '&:active': {
          backgroundColor: isDisabled ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.AQUA.LIGHTEST,
          color: isDisabled ? _constants.COLOR.NEUTRAL.DARK : _constants.COLOR.TEAL.DARK
        }
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getPlaceholderStyles", function (base, _ref5) {
      var isDisabled = _ref5.isDisabled;
      var inverse = _this.props.inverse;

      var commonStyles = _objectSpread(_objectSpread({}, base), {}, {
        marginLeft: '2px',
        marginRight: '2px',
        whiteSpace: 'nowrap'
      });

      if (inverse) {
        return _objectSpread(_objectSpread({}, commonStyles), {}, {
          color: isDisabled ? _constants.COLOR.TEAL.NORMAL : _constants.COLOR.TEAL.LIGHT
        });
      }

      return _objectSpread(_objectSpread({}, commonStyles), {}, {
        color: _constants.COLOR.NEUTRAL.DARKEST
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getSingleValueStyles", function (base) {
      return _objectSpread(_objectSpread({}, base), {}, {
        color: _this.props.inverse ? _constants.COLOR.NEUTRAL.LIGHTEST : _constants.COLOR.TEAL.DARKEST
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getValueContainerStyles", function (base, _ref6) {
      var isMulti = _ref6.isMulti,
          hasValue = _ref6.hasValue;
      var size = _this.props.size;
      return _objectSpread(_objectSpread({}, base), {}, {
        minHeight: minHeightBySizeMap[size] - 2,
        lineHeight: '18px',
        padding: isMulti && hasValue && size !== 'large' ? 0 : '0 4px'
      });
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "getStyles", function () {
      return {
        clearIndicator: _this.getClearIndicatorStyles,
        control: _this.getControlStyles,
        group: _this.getGroupStyles,
        groupHeading: _this.getGroupHeadingStyles,
        input: _this.getInput,
        menu: _this.getMenuStyles,
        menuPortal: _this.getMenuPortalStyles,
        multiValue: _this.getMultiValueStyles,
        multiValueLabel: _this.getMultiValueLabelStyles,
        multiValueRemove: _this.getMultiValueRemoveStyles,
        option: _this.getOptionStyles,
        placeholder: _this.getPlaceholderStyles,
        singleValue: _this.getSingleValueStyles,
        valueContainer: _this.getValueContainerStyles
      };
    });
    return _this;
  }

  (0, _createClass2.default)(Select, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      activeSelects.add(this);
      var isOverlayMounted = document.contains(selectOverlayNode);

      if (!isOverlayMounted) {
        document.body.appendChild(selectOverlayNode);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var isLastSelect = activeSelects.size <= 1;

      if (isLastSelect) {
        document.body.removeChild(selectOverlayNode);
      }

      activeSelects.delete(this);
    }
  }, {
    key: "render",
    value: function render() {
      var _cx;

      var _this$props5 = this.props,
          components = _this$props5.components,
          creatable = _this$props5.creatable,
          error = _this$props5.error,
          inverse = _this$props5.inverse,
          helpText = _this$props5.helpText,
          size = _this$props5.size,
          success = _this$props5.success,
          warning = _this$props5.warning,
          forwardedRef = _this$props5.forwardedRef,
          otherProps = (0, _objectWithoutProperties2.default)(_this$props5, _excluded);
      var boxProps = (0, _box.pickBoxProps)(otherProps);
      var restProps = (0, _box.omitBoxProps)(otherProps);
      var wrapperClassnames = (0, _classnames.default)(_theme.default["is-".concat(size)], (_cx = {}, (0, _defineProperty2.default)(_cx, _theme.default['has-error'], error), (0, _defineProperty2.default)(_cx, _theme.default['is-inverse'], inverse), _cx));
      var Element = creatable ? _creatable.default : _reactSelect.default;
      return /*#__PURE__*/_react.default.createElement(_box.default, (0, _extends2.default)({
        className: wrapperClassnames
      }, boxProps), /*#__PURE__*/_react.default.createElement(Element, (0, _extends2.default)({
        ref: forwardedRef,
        className: (0, _classnames.default)(_uiUtilities.default['reset-font-smoothing'], _theme.default['select']),
        components: _objectSpread({
          ClearIndicator: ClearIndicator,
          DropdownIndicator: DropdownIndicator,
          IndicatorSeparator: null
        }, components),
        hideSelectedOptions: false,
        menuPlacement: "auto",
        menuPortalTarget: selectOverlayNode,
        menuShouldBlockScroll: true,
        styles: this.getStyles(),
        size: size
      }, restProps)), /*#__PURE__*/_react.default.createElement(_validationText.default, {
        error: error,
        help: helpText,
        inverse: inverse,
        success: success,
        warning: warning
      }));
    }
  }]);
  return Select;
}(_react.PureComponent);

Select.defaultProps = {
  creatable: false,
  inverse: false,
  size: 'medium',
  width: '100%'
};
/** @type {React.ComponentType<any>} */

var ForwardedSelect = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  return /*#__PURE__*/_react.default.createElement(Select, (0, _extends2.default)({}, props, {
    forwardedRef: ref
  }));
});
ForwardedSelect.displayName = 'Select';
var _default = ForwardedSelect;
exports.default = _default;