function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import { Plugin, Widget, ButtonView, ContextualBalloon, Command, clickOutsideHandler, toWidget } from "../../ckeditor/ckeditor";
import OpenPanelCommand from "../OpenPanelCommand";
import FormView from "./FormView";
import "./index.less";
var Input = /*#__PURE__*/function (_Plugin) {
  _inherits(Input, _Plugin);
  var _super = _createSuper(Input);
  function Input() {
    _classCallCheck(this, Input);
    return _super.apply(this, arguments);
  }
  _createClass(Input, null, [{
    key: "requires",
    get: function get() {
      return [InputEditing, InputUI];
    }
  }]);
  return Input;
}(Plugin);
export { Input as default };
var InputEditing = /*#__PURE__*/function (_Plugin2) {
  _inherits(InputEditing, _Plugin2);
  var _super2 = _createSuper(InputEditing);
  function InputEditing() {
    _classCallCheck(this, InputEditing);
    return _super2.apply(this, arguments);
  }
  _createClass(InputEditing, [{
    key: "init",
    value: function init() {
      console.log('自定义文本框内容被调用');
      this._defineSchema();
      this._defineConverters();
      this.editor.commands.add('insertCustomInput', new InsertCustomInputCommand(this.editor));
      this.editor.commands.add('openInputPanel', new OpenPanelCommand(this.editor));
    }
  }, {
    key: "_defineSchema",
    value: function _defineSchema() {
      var schema = this.editor.model.schema;
      schema.register('customInput', {
        // 定义类型
        inheritAllFrom: '$inlineObject',
        // 定义属性
        allowAttributes: ['configid']
      });
    }
  }, {
    key: "_defineConverters",
    value: function _defineConverters() {
      var conversion = this.editor.conversion;

      // conversion.for('upcast').elementToElement({
      //     model: 'customInput',
      //     view: this._renderView
      // });
      conversion.for('upcast').elementToElement({
        view: {
          name: 'input',
          classes: 'custom-input'
        },
        model: function model(modelElement, props) {
          var writer = props === null || props === void 0 ? void 0 : props.writer;
          var configid = modelElement._attrs.get('configid');
          var element = null;
          if (writer) {
            element = writer.createElement('customInput', {
              configid: configid
            });
          }
          return element;
        }
      });
      conversion.for('dataDowncast').elementToElement({
        model: 'customInput',
        view: this._renderView
      });
      conversion.for('editingDowncast').elementToElement({
        model: 'customInput',
        view: this._renderView
      });
    }
  }, {
    key: "_renderView",
    value: function _renderView(modelElement, props) {
      var writer = props === null || props === void 0 ? void 0 : props.writer;
      var components = JSON.parse(sessionStorage.getItem('ckComponents') || '{}');
      var config = components[modelElement._attrs.get('configid')] || {};
      var obj = {
          configid: modelElement._attrs.get('configid')
        },
        style = '';
      for (var key in config) {
        if (key == 'width') {
          style += "width: ".concat(config[key], "px;");
        } else {
          if (key == 'label') {
            obj.placeholder = "\u8BF7\u8F93\u5165".concat(config[key] || '');
          }
          obj[key] = config[key];
        }
      }
      obj.style = style;
      var input = '';
      if (writer) {
        input = writer.createContainerElement('input', _objectSpread(_objectSpread({}, obj), {}, {
          class: 'custom-input has-border vtx_ck_widgets'
        }));
      }
      return toWidget(input, writer);
      // return input;
    }
  }], [{
    key: "requires",
    get: function get() {
      // ADDED
      return [Widget];
    }
  }]);
  return InputEditing;
}(Plugin);
function renderView(modelElement, props) {
  console.log('renderView');
  var writer = props === null || props === void 0 ? void 0 : props.writer;
  var attr = modelElement.getAttributes();
  console.log(attr);
  var obj = {},
    style = '';
  var _iterator = _createForOfIteratorHelper(attr),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _step$value = _slicedToArray(_step.value, 2),
        key = _step$value[0],
        value = _step$value[1];
      if (key == 'width') {
        style += "width: ".concat(value, ";");
      } else {
        if (key == 'label') {
          obj.placeholder = "\u8BF7\u8F93\u5165".concat(value || '');
        }
        obj[key] = value;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  obj.style = style;
  var input = '';
  if (writer) {
    input = writer.createEmptyElement('input', _objectSpread(_objectSpread({}, obj), {}, {
      class: 'custom-input has-border'
    }));
    console.log(input);
  }
  return input;
}
var InputUI = /*#__PURE__*/function (_Plugin3) {
  _inherits(InputUI, _Plugin3);
  var _super3 = _createSuper(InputUI);
  function InputUI() {
    _classCallCheck(this, InputUI);
    return _super3.apply(this, arguments);
  }
  _createClass(InputUI, [{
    key: "init",
    value: function init() {
      var _this = this;
      console.log('自定义文本框UI被调用');
      var editor = this.editor;
      var t = editor.t;
      this._balloon = this.editor.plugins.get(ContextualBalloon);
      this.formView = this._createFormView();
      editor.commands.get('openInputPanel').set('uiPanel', this);
      editor.ui.componentFactory.add('customInput', function (locale) {
        var buttonView = new ButtonView(locale);
        buttonView.set({
          label: t('文本框'),
          withText: true,
          tooltip: false
        });

        // this.listenTo(buttonView, 'execute', () => {
        //     editor.execute('insertCustomInput')
        // });
        _this.listenTo(buttonView, 'execute', function () {
          _this._showUI();
        });
        return buttonView;
      });
    }
  }, {
    key: "_createFormView",
    value: function _createFormView() {
      var _this2 = this;
      var editor = this.editor;
      var formView = new FormView(editor.locale);
      var _editor$config$get = editor.config.get('globalConfig'),
        emit = _editor$config$get.emit;
      this.listenTo(formView, 'submit', function () {
        var name = formView.nameInputView.fieldView.element.value;
        var label = formView.labelInputView.fieldView.element.value;
        var width = formView.widthInputView.fieldView.element.value;
        var order = formView.orderInputView.fieldView.element.value;
        emit('plugingChange', {
          config: {
            name: name,
            width: width,
            label: label,
            order: order,
            type: 'input'
          },
          callback: function callback(id) {
            editor.model.change(function (writer) {
              editor.execute('insertCustomInput', {
                configid: id
              });
            });
          }
        });
        _this2._hideUI();
      });
      this.listenTo(formView, 'cancel', function () {
        _this2._hideUI();
      });
      clickOutsideHandler({
        emitter: formView,
        activator: function activator() {
          return _this2._balloon.visibleView === formView;
        },
        contextElements: [this._balloon.view.element],
        callback: function callback() {
          return _this2._hideUI();
        }
      });
      return formView;
    }
  }, {
    key: "_getBalloonPositionData",
    value: function _getBalloonPositionData() {
      var view = this.editor.editing.view;
      var viewDocument = view.document;
      var target = null;

      // Set a target position by converting view selection range to DOM.
      target = function target() {
        return view.domConverter.viewRangeToDom(viewDocument.selection.getFirstRange());
      };
      return {
        target: target
      };
    }
  }, {
    key: "_showUI",
    value: function _showUI() {
      this._balloon.add({
        view: this.formView,
        position: this._getBalloonPositionData()
      });

      // this.formView.focus();
    }
  }, {
    key: "_hideUI",
    value: function _hideUI() {
      this.formView.widthInputView.fieldView.value = '';
      this.formView.nameInputView.fieldView.value = '';
      this.formView.labelInputView.fieldView.value = '';
      this.formView.orderInputView.fieldView.value = '';
      this.formView.element.reset();
      this._balloon.remove(this.formView);

      // Focus the editing view after closing the form view.
      this.editor.editing.view.focus();
    }
  }], [{
    key: "requires",
    get: function get() {
      return [ContextualBalloon];
    }
  }]);
  return InputUI;
}(Plugin);
var InsertCustomInputCommand = /*#__PURE__*/function (_Command) {
  _inherits(InsertCustomInputCommand, _Command);
  var _super4 = _createSuper(InsertCustomInputCommand);
  function InsertCustomInputCommand() {
    _classCallCheck(this, InsertCustomInputCommand);
    return _super4.apply(this, arguments);
  }
  _createClass(InsertCustomInputCommand, [{
    key: "execute",
    value: function execute(param) {
      var _this3 = this;
      this.editor.model.change(function (writer) {
        _this3.editor.model.insertObject(createCustomInputElement(writer, param));
      });
    }
  }]);
  return InsertCustomInputCommand;
}(Command);
function createCustomInputElement(writer, param) {
  var element = writer.createElement('customInput', param);
  return element;
}