'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SelectWithState = undefined;

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

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _reactSelect = require('react-select');

var _reactSelect2 = _interopRequireDefault(_reactSelect);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Select that uses https://github.com/JedWatson/react-select
// with default states and handles the current value as a local state.
//
// Also handles multi-level options. You can give `children: []` to each option
// and fill it with options to represent a hierarchy.
//
// E.g:
//    <SelectWithState options={
//      { label: 'Cat',
//        children: [{ label: 'A' }, { label: 'B' }]
//      } />
//


var SelectWithState = exports.SelectWithState = function (_Component) {
  _inherits(SelectWithState, _Component);

  function SelectWithState(props) {
    _classCallCheck(this, SelectWithState);

    var _this = _possibleConstructorReturn(this, (SelectWithState.__proto__ || Object.getPrototypeOf(SelectWithState)).call(this, props));

    _this.state = {
      value: props.value
    };

    _this.handleChange = _this.handleChange.bind(_this);
    _this.onKeyDown = _this.onKeyDown.bind(_this);
    return _this;
  }

  _createClass(SelectWithState, [{
    key: 'handleChange',
    value: function handleChange(val) {
      var value = val && val.value ? val : { value: null, label: null };

      this.setState({ value: value });
      this.props.onChange(value);
      this.props.onInputChange({ value: value, name: this.props.name });
    }
  }, {
    key: 'onKeyDown',
    value: function onKeyDown(event) {
      var enterKeyCode = 13;
      var spaceKeyCode = 32;

      if (event.keyCode === enterKeyCode || event.keyCode === spaceKeyCode) {
        event.preventDefault();
        event.stopPropagation();
        this.onRemove(event);
      }
    }
  }, {
    key: 'renderLabel',
    value: function renderLabel() {
      if (!this.props.labelText) return;

      return _react2.default.createElement(
        'label',
        { className: 'k-Select__label', id: this.props.id },
        this.props.labelText
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          value = _props.value,
          onChange = _props.onChange,
          className = _props.className,
          tiny = _props.tiny,
          error = _props.error,
          valid = _props.valid,
          disabled = _props.disabled,
          other = _objectWithoutProperties(_props, ['value', 'onChange', 'className', 'tiny', 'error', 'valid', 'disabled']);

      var selectClassName = (0, _classnames2.default)('k-Select', className, {
        'k-Select--tiny': tiny,
        'is-error': error,
        'is-valid': valid,
        'is-disabled': disabled
      });

      return _react2.default.createElement(
        'div',
        { className: selectClassName },
        this.renderLabel(),
        _react2.default.createElement(SelectWithMultiLevel, _extends({
          value: this.state.value,
          onKeyDown: this.onKeyDown,
          onChange: this.handleChange,
          disabled: disabled
        }, other))
      );
    }
  }]);

  return SelectWithState;
}(_react.Component);

var SelectWithMultiLevel = function (_Component2) {
  _inherits(SelectWithMultiLevel, _Component2);

  function SelectWithMultiLevel() {
    _classCallCheck(this, SelectWithMultiLevel);

    return _possibleConstructorReturn(this, (SelectWithMultiLevel.__proto__ || Object.getPrototypeOf(SelectWithMultiLevel)).apply(this, arguments));
  }

  _createClass(SelectWithMultiLevel, [{
    key: 'flattenedOptions',

    // Turns a hierarchy of options with `children` into a flat array
    // of options with a `level` of 1, 2 or null.
    value: function flattenedOptions() {
      var options = [];

      this.props.options.map(function (option) {
        if (option.children) {
          option.level = 1;
          options.push(option);
          option.children.map(function (opt) {
            opt.level = 2;
            options.push(opt);
          });
        } else {
          options.push(option);
        }
      });

      return options;
    }

    // React-Select allows changing the way options are rendered.

  }, {
    key: 'optionRenderer',
    value: function optionRenderer(_ref) {
      var level = _ref.level,
          label = _ref.label;

      if (!level) return label;

      return _react2.default.createElement(
        'span',
        { className: 'k-Select__option--level' + level },
        label
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var inputProps = this.props.inputProps;

      if (this.props.labelText && !inputProps['aria-labelledby']) inputProps['aria-labelledby'] = this.props.id;

      return _react2.default.createElement(_reactSelect2.default, _extends({
        optionRenderer: this.optionRenderer
      }, this.props, {
        inputProps: inputProps,
        options: this.flattenedOptions()
      }));
    }
  }]);

  return SelectWithMultiLevel;
}(_react.Component);

SelectWithState.defaultProps = {
  onChange: function onChange() {},
  onInputChange: function onInputChange() {},
  clearable: false,
  searchable: false,
  deleteRemoves: false,
  multi: false,
  labelText: null,
  error: false,
  valid: false,
  disabled: false,
  tiny: false,
  name: null,
  inputProps: {}

  // DEPRECATED: do not use default export.
};exports.default = SelectWithState;