Liferay.Loader.define("layout-content-page-editor-web@2.0.102/page_editor/app/processors/getAlloyEditorProcessor", ['module', 'exports', 'require', 'frontend-js-web', '../config/index'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = getAlloyEditorProcessor;

    var _frontendJsWeb = require("frontend-js-web");

    var _index = require("../config/index");

    var _window$CKEDITOR$SHIF, _window$CKEDITOR;

    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) {
            _defineProperty(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 _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;
    }

    var KEY_ENTER = 13;
    var KEY_SPACE = 32;
    var KEY_SHIFT_ENTER = ((_window$CKEDITOR$SHIF = (_window$CKEDITOR = window.CKEDITOR) === null || _window$CKEDITOR === void 0 ? void 0 : _window$CKEDITOR.SHIFT) !== null && _window$CKEDITOR$SHIF !== void 0 ? _window$CKEDITOR$SHIF : 0) + KEY_ENTER;

    var defaultGetEditorWrapper = function defaultGetEditorWrapper(element) {
      var wrapper = document.createElement('div');
      wrapper.innerHTML = element.innerHTML;
      element.innerHTML = '';
      element.appendChild(wrapper);
      return wrapper;
    };

    var defaultRender = function defaultRender(element, value) {
      element.innerHTML = value;
    };

    var keyupHandler = function keyupHandler(event) {
      if (event.keyCode === KEY_SPACE) {
        event.preventDefault();
      }
    };
    /**
     * @param {'text'|'rich-text'} editorConfigurationName
     * @param {function} [getEditorWrapper=defaultGetEditorWrapper] Optionally
     *  override getEditorWrapper function, where the editor will be instanciated
     * @param {function} [render=defaultRender] Optionally override render function
     */

    function getAlloyEditorProcessor(editorConfigurationName) {
      var getEditorWrapper = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetEditorWrapper;

      var _render = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultRender;

      var _editor;

      var _eventHandlers;

      var _element;

      var _callbacks = {};
      return {
        createEditor: function createEditor(element, changeCallback, destroyCallback, clickPosition) {
          _callbacks.changeCallback = changeCallback;
          _callbacks.destroyCallback = destroyCallback;

          if (_editor) {
            return;
          }

          var editorConfig = _index.config.defaultEditorConfigurations[editorConfigurationName].editorConfig;
          _element = element;
          var editorName = "".concat(_index.config.portletNamespace, "FragmentEntryLinkEditable_").concat(element.id);
          var editorWrapper = getEditorWrapper(element);
          editorWrapper.setAttribute('id', editorName);
          editorWrapper.setAttribute('name', editorName);
          element.addEventListener('keyup', keyupHandler);
          _editor = AlloyEditor.editable(editorWrapper, _objectSpread(_objectSpread({}, editorConfig), {}, {
            documentBrowseLinkCallback: function documentBrowseLinkCallback(editor, url, changeLinkCallback) {
              (0, _frontendJsWeb.openSelectionModal)({
                onSelect: changeLinkCallback,
                selectEventName: editor.title + 'selectItem',
                title: Liferay.Language.get('select-item'),
                url: url
              });
            },
            documentBrowseLinkUrl: editorConfig.documentBrowseLinkUrl.replace('_EDITOR_NAME_', editorName),
            filebrowserImageBrowseLinkUrl: editorConfig.filebrowserImageBrowseLinkUrl.replace('_EDITOR_NAME_', editorName),
            filebrowserImageBrowseUrl: editorConfig.filebrowserImageBrowseUrl.replace('_EDITOR_NAME_', editorName),
            title: editorName
          }));

          var nativeEditor = _editor.get('nativeEditor');

          _eventHandlers = [nativeEditor.on('key', function (event) {
            if ((event.data.keyCode === KEY_ENTER || event.data.keyCode === KEY_SHIFT_ENTER) && _element && (_element.getAttribute('type') === 'text' || _element.dataset.lfrEditableType === 'text')) {
              event.cancel();
            }
          }), nativeEditor.on('blur', function () {
            if (_editor._mainUI.state.hidden) {
              if (_callbacks.changeCallback) {
                _callbacks.changeCallback(nativeEditor.getData());
              }

              requestAnimationFrame(function () {
                if (_callbacks.destroyCallback) {
                  _callbacks.destroyCallback();
                }
              });
            }
          }), nativeEditor.on('instanceReady', function () {
            nativeEditor.focus();

            if (clickPosition) {
              _selectRange(clickPosition, nativeEditor);
            } else {
              nativeEditor.execCommand('selectAll');
            }
          })];

          _eventHandlers.push(nativeEditor.on('saveSnapshot', (0, _frontendJsWeb.debounce)(function () {
            if (_callbacks.changeCallback) {
              _callbacks.changeCallback(nativeEditor.getData());
            }
          }, 100)));
        },

        /**
         */
        destroyEditor: function destroyEditor(element, editableConfig) {
          if (_editor) {
            var lastValue = _editor.get('nativeEditor').getData();

            _editor.destroy();

            _eventHandlers.forEach(function (handler) {
              handler.removeListener();
            });

            _render(_element, lastValue, editableConfig);

            _editor = null;
            _eventHandlers = null;
            _element = null;
            _callbacks = {};
          }

          if (element) {
            element.removeEventListener('keyup', keyupHandler);
          }
        },

        /**
         * @param {HTMLElement} element HTMLElement that should be mutated with the
         *  given value.
         * @param {string} value Element content
         * @param {Object} editableConfig
         */
        render: function render(element, value, editableConfig) {
          if (element !== _element) {
            _render(element, value, editableConfig);
          }
        }
      };
    }
    /**
     * Place the caret in the click position
     * @param {Event} event
     * @param {CKEditor} nativeEditor
     */

    function _selectRange(clickPosition, nativeEditor) {
      var ckRange = nativeEditor.getSelection().getRanges()[0];

      if (document.caretPositionFromPoint) {
        var range = document.caretPositionFromPoint(clickPosition.clientX, clickPosition.clientY);
        var node = range.offsetNode;

        if (isTextNode(node)) {
          ckRange.setStart(CKEDITOR.dom.node(node), range.offset);
          ckRange.setEnd(CKEDITOR.dom.node(node), range.offset);
        }
      } else if (document.caretRangeFromPoint) {
        var _range = document.caretRangeFromPoint(clickPosition.clientX, clickPosition.clientY);

        var offset = _range.startOffset || 0;

        if (isTextNode(_range.startContainer) && isTextNode(_range.endContainer)) {
          ckRange.setStart(CKEDITOR.dom.node(_range.startContainer), offset);
          ckRange.setEnd(CKEDITOR.dom.node(_range.endContainer), offset);
        }
      }

      nativeEditor.getSelection().selectRanges([ckRange]);
    }

    function isTextNode(node) {
      return node.nodeType === Node.TEXT_NODE;
    }
    //# sourceMappingURL=getAlloyEditorProcessor.js.map
  }
});
//# sourceMappingURL=getAlloyEditorProcessor.js.map