"use strict";

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

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiCodeEditor", {
  enumerable: true,
  get: function get() {
    return _code_editor.EuiCodeEditor;
  }
});
exports.OuiCodeEditor = void 0;

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

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

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 _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 _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");

var _code_editor = require("../../eui_components/code_editor/code_editor");

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

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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /*
                                                                                                                                                                                                                                                                                                                                      * SPDX-License-Identifier: Apache-2.0
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * The OpenSearch Contributors require contributions made to
                                                                                                                                                                                                                                                                                                                                      * this file be licensed under the Apache-2.0 license or a
                                                                                                                                                                                                                                                                                                                                      * compatible open source license.
                                                                                                                                                                                                                                                                                                                                      *
                                                                                                                                                                                                                                                                                                                                      * Modifications Copyright OpenSearch Contributors. See
                                                                                                                                                                                                                                                                                                                                      * GitHub history for details.
                                                                                                                                                                                                                                                                                                                                      */ /*
                                                                                                                                                                                                                                                                                                                                          * Licensed to Elasticsearch B.V. under one or more contributor
                                                                                                                                                                                                                                                                                                                                          * license agreements. See the NOTICE file distributed with
                                                                                                                                                                                                                                                                                                                                          * this work for additional information regarding copyright
                                                                                                                                                                                                                                                                                                                                          * ownership. Elasticsearch B.V. licenses this file to you under
                                                                                                                                                                                                                                                                                                                                          * the Apache License, Version 2.0 (the "License"); you may
                                                                                                                                                                                                                                                                                                                                          * not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                                          * You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          *    http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                          * Unless required by applicable law or agreed to in writing,
                                                                                                                                                                                                                                                                                                                                          * software distributed under the License is distributed on an
                                                                                                                                                                                                                                                                                                                                          * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
                                                                                                                                                                                                                                                                                                                                          * KIND, either express or implied.  See the License for the
                                                                                                                                                                                                                                                                                                                                          * specific language governing permissions and limitations
                                                                                                                                                                                                                                                                                                                                          * under the License.
                                                                                                                                                                                                                                                                                                                                          */

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 OuiCodeEditor = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(OuiCodeEditor, _Component);

  var _super = _createSuper(OuiCodeEditor);

  function OuiCodeEditor() {
    var _this;

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

    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), "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), "onEscToExit", function () {
      _this.stopEditing();

      if (_this.editorHint) {
        _this.editorHint.focus();
      }
    });
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "onKeydownAce", function (event) {
      if (event.key === _services.keys.ESCAPE) {
        event.preventDefault();
        event.stopPropagation(); // Handles exiting edit mode when `isReadOnly` is set.
        // Other 'esc' cases handled by `stopEditingOnEsc` command.
        // Would run after `stopEditingOnEsc`.

        if (_this.aceEditor !== null && !_this.aceEditor.editor.completer && _this.state.isEditing) {
          _this.onEscToExit();
        }
      }
    });
    (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), "startEditing", function () {
      _this.setState({
        isHintActive: false
      });

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

  (0, _createClass2.default)(OuiCodeEditor, [{
    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,
          _this$props2$commands = _this$props2.commands,
          commands = _this$props2$commands === void 0 ? [] : _this$props2$commands,
          rest = (0, _objectWithoutProperties2.default)(_this$props2, ["width", "height", "onBlur", "isReadOnly", "setOptions", "cursorStart", "mode", "data-test-subj", "theme", "commands"]);
      var classes = (0, _classnames.default)('ouiCodeEditorWrapper', {
        'ouiCodeEditorWrapper-isEditing': this.state.isEditing
      });
      var promptClasses = (0, _classnames.default)('ouiCodeEditorKeyboardHint', {
        'ouiCodeEditorKeyboardHint-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;
      }

      var prompt = /*#__PURE__*/_react.default.createElement("button", {
        className: promptClasses,
        id: this.idGenerator('codeEditor'),
        ref: function ref(hint) {
          _this2.editorHint = hint;
        },
        onClick: this.startEditing,
        "data-test-subj": "codeEditorHint"
      }, /*#__PURE__*/_react.default.createElement("p", {
        className: "ouiText"
      }, isReadOnly ? /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCodeEditor.startInteracting",
        default: "Press Enter to start interacting with the code."
      }) : /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCodeEditor.startEditing",
        default: "Press Enter to start editing."
      })), /*#__PURE__*/_react.default.createElement("p", {
        className: "ouiText"
      }, isReadOnly ? /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCodeEditor.stopInteracting",
        default: "When you're done, press Escape to stop interacting with the code."
      }) : /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
        token: "ouiCodeEditor.stopEditing",
        default: "When you're done, press Escape to stop editing."
      })));

      return /*#__PURE__*/_react.default.createElement("div", {
        className: classes,
        style: {
          width: width,
          height: height
        },
        "data-test-subj": dataTestSubj
      }, prompt, /*#__PURE__*/_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,
        commands: [// Handles exiting edit mode in all cases except `isReadOnly`
        // Runs before `onKeydownAce`.
        {
          name: 'stopEditingOnEsc',
          bindKey: {
            win: 'Esc',
            mac: 'Esc'
          },
          exec: this.onEscToExit
        }].concat((0, _toConsumableArray2.default)(commands))
      }, rest)));
    }
  }]);
  return OuiCodeEditor;
}(_react.Component);
/* OUI -> EUI Aliases: Build-Time */


exports.OuiCodeEditor = OuiCodeEditor;
(0, _defineProperty2.default)(OuiCodeEditor, "defaultProps", {
  setOptions: {}
});
OuiCodeEditor.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
};
/* OUI -> EUI Aliases: Build-Time */