"use strict";

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

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

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

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

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

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

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

var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _defer = _interopRequireDefault(require("lodash/defer"));

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

var _lib = _interopRequireDefault(require("@instructure/ui-themeable/lib"));

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

var _Errors = _interopRequireDefault(require("../../../../../../common/components/shared/errors/Errors"));

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));

var _dec, _class, _class2, _temp;

var styles = {
  componentId: 'ddZoM',
  template: function template(theme) {
    return "\n\n.ddZoM_eqoe{border-bottom:solid;border-color:".concat(theme.titleEditWrapperBorderColor || 'inherit', ";border-width:").concat(theme.titleEditWrapperBorderWidth || 'inherit', ";box-sizing:border-box;display:flex;flex-direction:column;height:5rem;justify-content:center;padding-left:").concat(theme.titleEditWrapperLeftPadding || 'inherit', ";position:relative;width:100%}\n\n.ddZoM_dwFS{font-family:inherit;font-size:").concat(theme.titleEditInputFontSize || 'inherit', ";width:80%}\n\n.ddZoM_dRxD,.ddZoM_dvSU{display:flex;flex:1 1 auto;flex-direction:column;justify-content:center;width:100%}\n\n.ddZoM_xXob{border:solid 1px ").concat(theme.errorBorderColor || 'inherit', ";border-radius:").concat(theme.errorBorderBorderRadius || 'inherit', ";margin:").concat(theme.errorBorderMargin || 'inherit', ";padding:").concat(theme.errorBorderPadding || 'inherit', "}");
  },
  'titleEditWrapper': 'ddZoM_eqoe',
  'titleEditInput': 'ddZoM_dwFS',
  'errorsWrapper': 'ddZoM_dRxD',
  'inputWrapper': 'ddZoM_dvSU',
  'errorBorder': 'ddZoM_xXob'
};
// =================================
// once editing is toggled this div
// is rendered & has actions that
// allow for canceling
// =================================
var TitleEdit = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(TitleEdit, _Component);

  function TitleEdit() {
    var _getPrototypeOf2;

    var _this;

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

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

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(TitleEdit)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _this.defer = function (fn) {
      // to enable syncronous testing
      var deferFn = _this.props.deferMock || _defer.default;
      deferFn(fn);
    };

    _this.switchOffEditing = function () {
      var fromEnterPressed = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;

      _this.ifValidElseError(function () {
        _this.defer(function () {
          if (fromEnterPressed) {
            _this.props.saveAndPreview(fromEnterPressed);
          } else {
            // make sure they have actually left the component
            if (document.activeElement !== _this.cancelButton && document.activeElement !== _this.input) {
              _this.props.saveAndPreview();
            }
          }
        });
      });
    };

    _this.handleKeyUp = function (e) {
      if (_this.enterPressed && e.keyCode === 13) {
        return _this.switchOffEditing(true);
      }
    };

    _this.handleKeyDown = function (e) {
      if (!e.repeat && e.keyCode === 13) {
        _this.enterPressed = true;
      }
    };

    _this.handleBlur = function (e) {
      _this.switchOffEditing(false);
    };

    return _this;
  }

  (0, _createClass2.default)(TitleEdit, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var input = _reactDom.default.findDOMNode(this.input); // some browsers add chars so * 2 to ensure at end


      var valLength = input.value.length * 2;
      input.focus();
      input.setSelectionRange(valLength, valLength);
    }
  }, {
    key: "ifValidElseError",
    value: function ifValidElseError(cb) {
      if (this.props.isValid) {
        this.props.hideError();
        cb();
      } else {
        this.props.showError();
      }
    }
  }, {
    key: "setRef",
    value: function setRef(key) {
      var _this2 = this;

      return function (node) {
        _this2[key] = node;
      };
    }
  }, {
    key: "hasErrors",
    value: function hasErrors() {
      return this.props.errorsAreShowing && this.props.errors.size > 0;
    }
  }, {
    key: "renderErrors",
    value: function renderErrors() {
      if (this.hasErrors()) {
        return _react.default.createElement("div", {
          className: styles.errorsWrapper
        }, _react.default.createElement(_Errors.default, {
          errorList: this.props.errors
        }));
      }
    }
  }, {
    key: "inputClasses",
    value: function inputClasses() {
      var _classNames;

      return (0, _classnames.default)((_classNames = {}, (0, _defineProperty2.default)(_classNames, styles.titleEditInput, true), (0, _defineProperty2.default)(_classNames, styles.errorBorder, this.hasErrors()), _classNames));
    }
  }, {
    key: "render",
    value: function render() {
      return _react.default.createElement("div", {
        ref: this.setRef('wrapper'),
        className: styles.titleEditWrapper,
        onBlur: this.handleBlur,
        "data-automation": "sdk-quiz-title-edit-wrapper"
      }, _react.default.createElement("div", {
        className: styles.inputWrapper
      }, _react.default.createElement("input", {
        ref: this.setRef('input'),
        type: "text",
        "aria-label": "\u6807\u9898",
        placeholder: "\u6DFB\u52A0\u6807\u9898...",
        value: this.props.value,
        onKeyDown: this.handleKeyDown,
        onKeyUp: this.handleKeyUp,
        onChange: this.props.onInputChange,
        className: this.inputClasses(),
        "data-automation": "sdk-quiz-title-edit"
      })), this.renderErrors());
    }
  }]);
  TitleEdit.displayName = "TitleEdit";
  return TitleEdit;
}(_react.Component), _class2.propTypes = {
  value: _propTypes.default.string.isRequired,
  isValid: _propTypes.default.bool.isRequired,
  showError: _propTypes.default.func.isRequired,
  hideError: _propTypes.default.func.isRequired,
  errors: _reactImmutableProptypes.default.list.isRequired,
  errorsAreShowing: _propTypes.default.bool,
  onInputChange: _propTypes.default.func.isRequired,
  saveAndPreview: _propTypes.default.func.isRequired,
  deferMock: _propTypes.default.func
}, _class2.defaultProps = {
  errorsAreShowing: false,
  deferMock: _defer.default // todo: extract this into a shared method
  // to be used on many components

}, _temp)) || _class);
exports.TitleEdit = TitleEdit;
var _default = TitleEdit;
exports.default = _default;