'use strict';

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

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 _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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _cspaceLayout = require('cspace-layout');

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _TextInput = require('./TextInput');

var _TextInput2 = _interopRequireDefault(_TextInput);

var _DropdownInput = require('../../styles/cspace-input/DropdownInput.css');

var _DropdownInput2 = _interopRequireDefault(_DropdownInput);

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

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

var propTypes = _extends({}, _TextInput2.default.propTypes, {
  children: _react.PropTypes.node,
  className: _react.PropTypes.string,
  embedded: _react.PropTypes.bool,
  open: _react.PropTypes.bool,
  openOnFocus: _react.PropTypes.bool,

  /*
   * A function that may be called to give focus to the contents of the popup. This is supplied as
   * a prop because DropdownInput does not know the contents of the popup. Only the caller knows
   * which element in the popup should receive focus.
   */
  focusPopup: _react.PropTypes.func,

  onBlur: _react.PropTypes.func,
  onClose: _react.PropTypes.func,
  onKeyDown: _react.PropTypes.func,
  onMount: _react.PropTypes.func,
  onOpen: _react.PropTypes.func
});

var defaultProps = {
  className: '',
  open: false
};

var DropdownInput = function (_Component) {
  _inherits(DropdownInput, _Component);

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

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

    _this.handleInputBlur = _this.handleInputBlur.bind(_this);
    _this.handleInputFocus = _this.handleInputFocus.bind(_this);
    _this.handleInputMouseDown = _this.handleInputMouseDown.bind(_this);
    _this.handleInputKeyDown = _this.handleInputKeyDown.bind(_this);
    _this.handlePopupBlur = _this.handlePopupBlur.bind(_this);
    _this.handlePopupKeyDown = _this.handlePopupKeyDown.bind(_this);
    _this.handlePopupMount = _this.handlePopupMount.bind(_this);
    _this.handleRef = _this.handleRef.bind(_this);

    _this.state = {
      open: props.open
    };
    return _this;
  }

  _createClass(DropdownInput, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var onMount = this.props.onMount;


      if (onMount) {
        onMount({
          focusInput: this.focusInput.bind(this)
        });
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        open: nextProps.open
      });
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevState.open && !this.state.open) {
        var onClose = this.props.onClose;


        if (onClose) {
          onClose();
        }
      }
    }
  }, {
    key: 'close',
    value: function close() {
      var _this2 = this;

      if (this.state.open) {
        setTimeout(function () {
          _this2.setState({
            open: false
          });
        }, 0);
      }
    }
  }, {
    key: 'open',
    value: function open() {
      if (!this.state.open) {
        var onOpen = this.props.onOpen;


        if (onOpen) {
          onOpen();
        }

        this.setState({
          open: true
        });
      }
    }
  }, {
    key: 'focusInput',
    value: function focusInput() {
      // FIXME: This breaks the TextInput component abstraction by selecting the rendered DOM node
      // directly and calling focus() on it. But fixing this would require saving a ref to the
      // TextInput; making TextInput a class instead of a function; and adding a focus() method to
      // that class, which could be called here. LineInput and MultilineInput would also need to
      // become classes instead of functions, each with their own focus() method, in order to
      // properly implement TextInput.focus(). This seems like overkill at the moment.

      this.domNode.querySelector('input, textarea').focus();
    }
  }, {
    key: 'focusPopup',
    value: function focusPopup() {
      var focusPopup = this.props.focusPopup;


      if (focusPopup) {
        focusPopup();
      }
    }
  }, {
    key: 'handleInputBlur',
    value: function handleInputBlur(event) {
      var onBlur = this.props.onBlur;


      if (onBlur) {
        onBlur(event);
      }

      if (!this.domNode.contains(event.relatedTarget)) {
        this.close();
      }
    }
  }, {
    key: 'handleInputFocus',
    value: function handleInputFocus() {
      var openOnFocus = this.props.openOnFocus;


      if (openOnFocus) {
        this.open();
      }
    }
  }, {
    key: 'handleInputMouseDown',
    value: function handleInputMouseDown() {
      this.open();
    }
  }, {
    key: 'handleInputKeyDown',
    value: function handleInputKeyDown(event) {
      var onKeyDown = this.props.onKeyDown;


      if (event.key === 'ArrowDown') {
        // Prevent the page from scrolling.
        event.preventDefault();

        if (this.state.open) {
          this.focusPopup();
        } else {
          this.open();
          this.focusPopupNeeded = true;
        }
      } else if (event.key === 'Escape') {
        this.close();
      }

      if (onKeyDown) {
        onKeyDown(event);
      }
    }
  }, {
    key: 'handlePopupBlur',
    value: function handlePopupBlur(event) {
      if (!this.domNode.contains(event.relatedTarget)) {
        this.close();
      }
    }
  }, {
    key: 'handlePopupKeyDown',
    value: function handlePopupKeyDown(event) {
      if (event.key === 'Escape') {
        this.close();
        this.focusInput();
      }
    }
  }, {
    key: 'handlePopupMount',
    value: function handlePopupMount() {
      if (this.focusPopupNeeded) {
        this.focusPopup();
        this.focusPopupNeeded = false;
      }
    }
  }, {
    key: 'handleRef',
    value: function handleRef(ref) {
      this.domNode = ref;
    }
  }, {
    key: 'renderInput',
    value: function renderInput() {
      var _props = this.props,
          children = _props.children,
          className = _props.className,
          focusPopup = _props.focusPopup,
          openOnFocus = _props.openOnFocus,
          onClose = _props.onClose,
          onKeyDown = _props.onKeyDown,
          onMount = _props.onMount,
          onOpen = _props.onOpen,
          remainingProps = _objectWithoutProperties(_props, ['children', 'className', 'focusPopup', 'openOnFocus', 'onClose', 'onKeyDown', 'onMount', 'onOpen']);

      return _react2.default.createElement(_TextInput2.default, _extends({}, remainingProps, {
        onBlur: this.handleInputBlur,
        onFocus: this.handleInputFocus,
        onKeyDown: this.handleInputKeyDown,
        onMouseDown: this.handleInputMouseDown
      }));
    }
  }, {
    key: 'renderDropdown',
    value: function renderDropdown() {
      var open = this.state.open;
      var children = this.props.children;


      if (open) {
        return _react2.default.createElement(
          _cspaceLayout.Popup,
          {
            onBlur: this.handlePopupBlur,
            onKeyDown: this.handlePopupKeyDown,
            onMount: this.handlePopupMount
          },
          children
        );
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _classNames;

      var open = this.state.open;
      var _props2 = this.props,
          className = _props2.className,
          embedded = _props2.embedded;


      var classes = (0, _classnames2.default)(className, (_classNames = {}, _defineProperty(_classNames, _DropdownInput2.default.normal, !embedded), _defineProperty(_classNames, _DropdownInput2.default.embedded, embedded), _defineProperty(_classNames, _DropdownInput2.default.open, open), _classNames));

      return _react2.default.createElement(
        'div',
        {
          ref: this.handleRef,
          className: classes
        },
        this.renderInput(),
        this.renderDropdown()
      );
    }
  }]);

  return DropdownInput;
}(_react.Component);

exports.default = DropdownInput;


DropdownInput.propTypes = propTypes;
DropdownInput.defaultProps = defaultProps;