"use strict";

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

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

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

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

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

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

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

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

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

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

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

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

var _reactAce = _interopRequireDefault(require("react-ace"));

var _common = require("../common");

var _services = require("../../services");

var _i18n = require("../i18n");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var DEFAULT_MODE = 'text';
var DEFAULT_THEME = 'textmate';

function setOrRemoveAttribute(element, attributeName, value) {
  if (value === null || value === undefined) {
    element.removeAttribute(attributeName);
  } else {
    element.setAttribute(attributeName, value);
  }
}

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

  function EuiCodeEditor() {
    var _getPrototypeOf2;

    var _this;

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

    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)(EuiCodeEditor)).call.apply(_getPrototypeOf2, [this].concat(args)));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", {
      isHintActive: true,
      isEditing: false,
      name: (0, _services.htmlIdGenerator)()()
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "idGenerator", (0, _services.htmlIdGenerator)());
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "aceEditor", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "editorHint", null);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "aceEditorRef", function (aceEditor) {
      if (aceEditor) {
        _this.aceEditor = aceEditor;
        var textbox = aceEditor.editor.textInput.getElement();
        textbox.tabIndex = -1;
        textbox.addEventListener('keydown', _this.onKeydownAce);
        setOrRemoveAttribute(textbox, 'aria-label', _this.props['aria-label']);
        setOrRemoveAttribute(textbox, 'aria-labelledby', _this.props['aria-labelledby']);
        setOrRemoveAttribute(textbox, 'aria-describedby', _this.props['aria-describedby']);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onKeydownAce", function (event) {
      if (event.key === _services.keys.ESCAPE) {
        // If the autocompletion context menu is open then we want to let ESCAPE close it but
        // **not** exit out of editing mode.
        if (_this.aceEditor !== null && !_this.aceEditor.editor.completer) {
          event.preventDefault();
          event.stopPropagation();

          _this.stopEditing();

          if (_this.editorHint) {
            _this.editorHint.focus();
          }
        }
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onFocusAce", function (event, editor) {
      _this.setState({
        isEditing: true
      });

      if (_this.props.onFocus) {
        _this.props.onFocus(event, editor);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onBlurAce", function (event, editor) {
      _this.stopEditing();

      if (_this.props.onBlur) {
        _this.props.onBlur(event, editor);
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onKeyDownHint", function (event) {
      if (event.key === _services.keys.ENTER) {
        event.preventDefault();

        _this.startEditing();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "startEditing", function () {
      _this.setState({
        isHintActive: false
      });

      if (_this.aceEditor !== null) {
        _this.aceEditor.editor.textInput.focus();
      }
    });
    return _this;
  }

  (0, _createClass2.default)(EuiCodeEditor, [{
    key: "stopEditing",
    value: function stopEditing() {
      this.setState({
        isHintActive: true,
        isEditing: false
      });
    }
  }, {
    key: "isCustomMode",
    value: function isCustomMode() {
      return (0, _typeof2.default)(this.props.mode) === 'object';
    }
  }, {
    key: "setCustomMode",
    value: function setCustomMode() {
      if (this.aceEditor !== null) {
        this.aceEditor.editor.getSession().setMode(this.props.mode);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.isCustomMode()) {
        this.setCustomMode();
      }

      var _this$props = this.props,
          isReadOnly = _this$props.isReadOnly,
          id = _this$props.id;
      var textareaProps = {
        id: id,
        readOnly: isReadOnly
      };
      var el = document.getElementById(this.state.name);

      if (el) {
        var textarea = el.querySelector('textarea');
        if (textarea) (0, _common.keysOf)(textareaProps).forEach(function (key) {
          if (textareaProps[key]) textarea.setAttribute("".concat(key), textareaProps[key].toString());
        });
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.props.mode !== prevProps.mode && this.isCustomMode()) {
        this.setCustomMode();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          width = _this$props2.width,
          height = _this$props2.height,
          onBlur = _this$props2.onBlur,
          isReadOnly = _this$props2.isReadOnly,
          setOptions = _this$props2.setOptions,
          cursorStart = _this$props2.cursorStart,
          _this$props2$mode = _this$props2.mode,
          mode = _this$props2$mode === void 0 ? DEFAULT_MODE : _this$props2$mode,
          _this$props2$dataTes = _this$props2['data-test-subj'],
          dataTestSubj = _this$props2$dataTes === void 0 ? 'codeEditorContainer' : _this$props2$dataTes,
          _this$props2$theme = _this$props2.theme,
          theme = _this$props2$theme === void 0 ? DEFAULT_THEME : _this$props2$theme,
          rest = (0, _objectWithoutProperties2.default)(_this$props2, ["width", "height", "onBlur", "isReadOnly", "setOptions", "cursorStart", "mode", "data-test-subj", "theme"]);
      var classes = (0, _classnames.default)('euiCodeEditorWrapper', {
        'euiCodeEditorWrapper-isEditing': this.state.isEditing
      });
      var promptClasses = (0, _classnames.default)('euiCodeEditorKeyboardHint', {
        'euiCodeEditorKeyboardHint-isInactive': !this.state.isHintActive
      });
      var filteredCursorStart;

      var options = _objectSpread({}, setOptions);

      if (isReadOnly) {
        // Put the cursor at the beginning of the editor, so that it doesn't look like
        // a prompt to begin typing.
        filteredCursorStart = -1;
        Object.assign(options, {
          readOnly: true,
          highlightActiveLine: false,
          highlightGutterLine: false
        });
      } else {
        filteredCursorStart = cursorStart;
      } // Don't use EuiKeyboardAccessible here because it doesn't play nicely with onKeyDown.


      var prompt = _react.default.createElement("div", {
        className: promptClasses,
        id: this.idGenerator('codeEditor'),
        ref: function ref(hint) {
          _this2.editorHint = hint;
        },
        tabIndex: 0,
        role: "button",
        onClick: this.startEditing,
        onKeyDown: this.onKeyDownHint,
        "data-test-subj": "codeEditorHint"
      }, _react.default.createElement("p", {
        className: "euiText"
      }, isReadOnly ? _react.default.createElement(_i18n.EuiI18n, {
        token: "euiCodeEditor.startInteracting",
        default: "Press Enter to start interacting with the code."
      }) : _react.default.createElement(_i18n.EuiI18n, {
        token: "euiCodeEditor.startEditing",
        default: "Press Enter to start editing."
      })), _react.default.createElement("p", {
        className: "euiText"
      }, isReadOnly ? _react.default.createElement(_i18n.EuiI18n, {
        token: "euiCodeEditor.stopInteracting",
        default: "When you're done, press Escape to stop interacting with the code."
      }) : _react.default.createElement(_i18n.EuiI18n, {
        token: "euiCodeEditor.stopEditing",
        default: "When you're done, press Escape to stop editing."
      })));

      return _react.default.createElement("div", {
        className: classes,
        style: {
          width: width,
          height: height
        },
        "data-test-subj": dataTestSubj
      }, prompt, _react.default.createElement(_reactAce.default // Setting a default, existing `mode` is necessary to properly initialize the editor
      // prior to dynamically setting a custom mode (https://github.com/elastic/eui/pull/2616)
      , (0, _extends2.default)({
        mode: this.isCustomMode() ? DEFAULT_MODE : mode // https://github.com/securingsincity/react-ace/pull/771
        ,
        name: this.state.name,
        theme: theme,
        ref: this.aceEditorRef,
        width: width,
        height: height,
        onFocus: this.onFocusAce,
        onBlur: this.onBlurAce,
        setOptions: options,
        editorProps: {
          $blockScrolling: Infinity
        },
        cursorStart: filteredCursorStart
      }, rest)));
    }
  }]);
  return EuiCodeEditor;
}(_react.Component);

exports.EuiCodeEditor = EuiCodeEditor;
(0, _defineProperty2.default)(EuiCodeEditor, "defaultProps", {
  setOptions: {}
});
EuiCodeEditor.propTypes = {
  width: _propTypes.default.string,
  height: _propTypes.default.string,
  onBlur: _propTypes.default.any,
  onFocus: _propTypes.default.any,
  isReadOnly: _propTypes.default.bool,
  setOptions: _propTypes.default.any.isRequired,
  cursorStart: _propTypes.default.number,
  "data-test-subj": _propTypes.default.string,

  /**
     * Select the `brace` theme
     * The matching theme file must also be imported from `brace` (e.g., `import 'brace/theme/github';`)
     */
  theme: _propTypes.default.any,

  /**
     * Use string for a built-in mode or object for a custom mode
     */
  mode: _propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.any.isRequired]),
  id: _propTypes.default.string
};
EuiCodeEditor.__docgenInfo = {
  "description": "",
  "methods": [{
    "name": "aceEditorRef",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "aceEditor",
      "type": null
    }],
    "returns": null
  }, {
    "name": "onKeydownAce",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "event",
      "type": null
    }],
    "returns": null
  }, {
    "name": "onFocusAce",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "event",
      "type": null
    }, {
      "name": "editor",
      "type": null
    }],
    "returns": null
  }, {
    "name": "onBlurAce",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "event",
      "type": null
    }, {
      "name": "editor",
      "type": null
    }],
    "returns": null
  }, {
    "name": "onKeyDownHint",
    "docblock": null,
    "modifiers": [],
    "params": [{
      "name": "event",
      "type": null
    }],
    "returns": null
  }, {
    "name": "startEditing",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }, {
    "name": "stopEditing",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }, {
    "name": "isCustomMode",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }, {
    "name": "setCustomMode",
    "docblock": null,
    "modifiers": [],
    "params": [],
    "returns": null
  }],
  "displayName": "EuiCodeEditor",
  "props": {
    "setOptions": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "type": {
        "name": "any"
      },
      "required": false,
      "description": ""
    },
    "width": {
      "type": {
        "name": "string"
      },
      "required": false,
      "description": ""
    },
    "height": {
      "type": {
        "name": "string"
      },
      "required": false,
      "description": ""
    },
    "onBlur": {
      "type": {
        "name": "any"
      },
      "required": false,
      "description": ""
    },
    "onFocus": {
      "type": {
        "name": "any"
      },
      "required": false,
      "description": ""
    },
    "isReadOnly": {
      "type": {
        "name": "bool"
      },
      "required": false,
      "description": ""
    },
    "cursorStart": {
      "type": {
        "name": "number"
      },
      "required": false,
      "description": ""
    },
    "data-test-subj": {
      "type": {
        "name": "string"
      },
      "required": false,
      "description": ""
    },
    "theme": {
      "type": {
        "name": "any"
      },
      "required": false,
      "description": "Select the `brace` theme\nThe matching theme file must also be imported from `brace` (e.g., `import 'brace/theme/github';`)"
    },
    "mode": {
      "type": {
        "name": "union",
        "value": [{
          "name": "any"
        }, {
          "name": "any"
        }]
      },
      "required": false,
      "description": "Use string for a built-in mode or object for a custom mode"
    },
    "id": {
      "type": {
        "name": "string"
      },
      "required": false,
      "description": ""
    }
  }
};