"use strict";

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

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

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

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

var _slateHotkeys = _interopRequireDefault(require("slate-hotkeys"));

var _slateDevEnvironment = require("slate-dev-environment");

var _slate = require("slate");

var _FormatBold = _interopRequireDefault(require("@material-ui/icons/FormatBold"));

var _FormatQuote = _interopRequireDefault(require("@material-ui/icons/FormatQuote"));

var _FormatListBulleted = _interopRequireDefault(require("@material-ui/icons/FormatListBulleted"));

var _FormatListNumbered = _interopRequireDefault(require("@material-ui/icons/FormatListNumbered"));

var _Redo = _interopRequireDefault(require("@material-ui/icons/Redo"));

var _Undo = _interopRequireDefault(require("@material-ui/icons/Undo"));

var _image = _interopRequireDefault(require("./image"));

var _media = _interopRequireDefault(require("./media"));

var _characters = _interopRequireDefault(require("./characters"));

var _FormatItalic = _interopRequireDefault(require("@material-ui/icons/FormatItalic"));

var _math = _interopRequireDefault(require("./math"));

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

var _FormatStrikethrough = _interopRequireDefault(require("@material-ui/icons/FormatStrikethrough"));

var _toolbar = _interopRequireDefault(require("./toolbar"));

var _FormatUnderlined = _interopRequireDefault(require("@material-ui/icons/FormatUnderlined"));

var _compact = _interopRequireDefault(require("lodash/compact"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

var _slateSoftBreak = _interopRequireDefault(require("slate-soft-break"));

var _debug = _interopRequireDefault(require("debug"));

var _list = _interopRequireDefault(require("./list"));

var _table = _interopRequireDefault(require("./table"));

var _respArea = _interopRequireDefault(require("./respArea"));

var _html = _interopRequireDefault(require("./html"));

var _css = _interopRequireDefault(require("./css"));

var _customPlugin = _interopRequireDefault(require("./customPlugin"));

var _rendering = _interopRequireDefault(require("./rendering"));

var _textAlign = _interopRequireDefault(require("./textAlign"));

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

var log = (0, _debug["default"])('@pie-lib:editable-html:plugins');

var SuperscriptIcon = function SuperscriptIcon() {
  return /*#__PURE__*/_react["default"].createElement("svg", {
    xmlns: "http://www.w3.org/2000/svg",
    height: "24px",
    viewBox: "0 0 24 24",
    width: "24px",
    fill: "none"
  }, /*#__PURE__*/_react["default"].createElement("path", {
    d: "M22,7h-2v1h3v1h-4V7c0-0.55,0.45-1,1-1h2V5h-3V4h3c0.55,0,1,0.45,1,1v1C23,6.55,22.55,7,22,7z M5.88,20h2.66l3.4-5.42h0.12 l3.4,5.42h2.66l-4.65-7.27L17.81,6h-2.68l-3.07,4.99h-0.12L8.85,6H6.19l4.32,6.73L5.88,20z",
    fill: "currentColor"
  }));
};

var SubscriptIcon = function SubscriptIcon() {
  return /*#__PURE__*/_react["default"].createElement("svg", {
    xmlns: "http://www.w3.org/2000/svg",
    height: "24px",
    viewBox: "0 0 24 24",
    width: "24px",
    fill: "none"
  }, /*#__PURE__*/_react["default"].createElement("path", {
    d: "M22,18h-2v1h3v1h-4v-2c0-0.55,0.45-1,1-1h2v-1h-3v-1h3c0.55,0,1,0.45,1,1v1C23,17.55,22.55,18,22,18z M5.88,18h2.66 l3.4-5.42h0.12l3.4,5.42h2.66l-4.65-7.27L17.81,4h-2.68l-3.07,4.99h-0.12L8.85,4H6.19l4.32,6.73L5.88,18z",
    fill: "currentColor"
  }));
};

var HeadingIcon = function HeadingIcon() {
  return /*#__PURE__*/_react["default"].createElement("svg", {
    width: "30",
    height: "28",
    viewBox: "0 0 30 28",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    style: {
      width: '20px',
      height: '18px'
    }
  }, /*#__PURE__*/_react["default"].createElement("path", {
    d: "M27 4V24H29C29.5 24 30 24.5 30 25V27C30 27.5625 29.5 28 29 28H19C18.4375 28 18 27.5625 18 27V25C18 24.5 18.4375 24 19 24H21V16H9V24H11C11.5 24 12 24.5 12 25V27C12 27.5625 11.5 28 11 28H1C0.4375 28 0 27.5625 0 27V25C0 24.5 0.4375 24 1 24H3V4H1C0.4375 4 0 3.5625 0 3V1C0 0.5 0.4375 0 1 0H11C11.5 0 12 0.5 12 1V3C12 3.5625 11.5 4 11 4H9V12H21V4H19C18.4375 4 18 3.5625 18 3V1C18 0.5 18.4375 0 19 0H29C29.5 0 30 0.5 30 1V3C30 3.5625 29.5 4 29 4H27Z",
    fill: "currentColor"
  }));
};

var STYLES_MAP = {
  h3: {
    fontSize: 'inherit',
    fontWeight: 'inherit'
  },
  blockquote: {
    background: '#f9f9f9',
    borderLeft: '5px solid #ccc',
    margin: '1.5em 10px',
    padding: '.5em 10px'
  }
};

function MarkHotkey(options) {
  var type = options.type,
      key = options.key,
      icon = options.icon,
      tag = options.tag; // Return our "plugin" object, containing the `onKeyDown` handler.

  return {
    name: type,
    toolbar: {
      isMark: true,
      type: type,
      icon: icon,
      onToggle: function onToggle(change) {
        log('[onToggleMark] type: ', type);
        var selection = change.value.selection;

        if (['blockquote', 'h3'].includes(type)) {
          var texts = change.value.document.getTextsAtRangeAsArray(selection);
          var onlyOneText = texts.length === 1;
          var hasMark = false;
          var sameMark = true;
          texts.forEach(function (t) {
            var marks = t.getMarksAsArray();
            var markIsThere = marks.find(function (m) {
              return m.type === type;
            });

            if (!markIsThere) {
              // not all texts have this mark
              sameMark = false;
            } else {
              // at least one mark
              hasMark = true;
            }
          });
          var shouldContinue = onlyOneText || sameMark || !hasMark;

          if (!shouldContinue) {
            return change;
          }

          if (selection.startKey === selection.endKey && selection.anchorOffset === selection.focusOffset) {
            var textNode = change.value.document.getNode(selection.startKey); // select the whole line if there is no selection

            change.moveFocusTo(textNode.key, 0).moveAnchorTo(textNode.key, textNode.text.length); // remove toggle

            var _hasMark = change.value.activeMarks.find(function (entry) {
              return entry.type === type;
            });

            if (_hasMark) {
              change.removeMark(_hasMark);
            } else {
              var newMark = _slate.Mark.create(type);

              change.addMark(newMark);
            } // move focus to end of text


            return change.moveFocusTo(textNode.key, textNode.text.length).moveAnchorTo(textNode.key, textNode.text.length);
          }
        }

        return change.toggleMark(type);
      }
    },
    renderMark: function renderMark(props) {
      if (props.mark.type === type) {
        var _ref = props.node || {},
            data = _ref.data;

        var jsonData = (data === null || data === void 0 ? void 0 : data.toJSON()) || {};
        var K = tag || type;
        var additionalStyles = STYLES_MAP[K];

        if (additionalStyles) {
          if (!jsonData.attributes) {
            jsonData.attributes = {};
          }

          jsonData.attributes.style = _objectSpread(_objectSpread({}, jsonData.attributes.style), additionalStyles);
        }

        return /*#__PURE__*/_react["default"].createElement(K, jsonData.attributes, props.children);
      }
    },
    onKeyDown: function onKeyDown(event, change) {
      // Check that the key pressed matches our `key` option.
      if (!event.metaKey || event.key != key) return; // Prevent the default characters from being inserted.

      event.preventDefault(); // Toggle the mark `type`.

      change.toggleMark(type);
      return true;
    }
  };
}

var ALL_PLUGINS = ['bold', // 'code',
'html', 'extraCSSRules', 'italic', 'underline', 'strikethrough', 'bulleted-list', 'numbered-list', 'image', 'math', 'languageCharacters', 'text-align', 'blockquote', 'h3', 'table', 'video', 'audio', 'responseArea', 'redo', 'undo', 'superscript', 'subscript'];
exports.ALL_PLUGINS = ALL_PLUGINS;
var DEFAULT_PLUGINS = ALL_PLUGINS.filter(function (plug) {
  return !['responseArea', 'h3', 'blockquote'].includes(plug);
});
exports.DEFAULT_PLUGINS = DEFAULT_PLUGINS;
var ICON_MAP = {
  undo: _Undo["default"],
  redo: _Redo["default"]
};

function UndoRedo(type) {
  var IconToUse = ICON_MAP[type];
  return {
    name: type,
    toolbar: {
      type: type,
      icon: /*#__PURE__*/_react["default"].createElement(IconToUse, null),
      ariaLabel: type === 'undo' ? 'Undo (revert the last action)' : 'Redo (reapply the last undone action)',
      onClick: function onClick(value, onChange) {
        var change = value.change();
        onChange(change[type]());
      }
    }
  };
}

function EnterHandlingPlugin() {
  return {
    name: 'enterHandling',
    onKeyDown: function onKeyDown(event, change) {
      if (_slateHotkeys["default"].isSplitBlock(event) && !_slateDevEnvironment.IS_IOS) {
        if (change.value.isInVoid) {
          return change.collapseToStartOfNextText();
        }

        change.splitBlock();
        var range = change.value.selection;
        var newBlock = change.value.document.getClosestBlock(range.startKey);

        if (newBlock.type !== 'paragraph') {
          change.setNodeByKey(newBlock.key, {
            type: 'paragraph'
          });
        }

        return change;
      }

      return undefined;
    }
  };
}

var buildPlugins = function buildPlugins(activePlugins, customPlugins, opts) {
  log('[buildPlugins] opts: ', opts);
  activePlugins = activePlugins || DEFAULT_PLUGINS;

  var addIf = function addIf(key, p) {
    return activePlugins.includes(key) && p;
  };

  var imagePlugin = opts.image && opts.image.onDelete && (0, _image["default"])(opts.image);
  var mathPlugin = (0, _math["default"])(opts.math);
  var respAreaPlugin = opts.responseArea && opts.responseArea.type && (0, _respArea["default"])(opts.responseArea, (0, _compact["default"])([mathPlugin]));
  var cssPlugin = !(0, _isEmpty["default"])(opts.extraCSSRules) && (0, _css["default"])(opts.extraCSSRules);
  var languageCharactersPlugins = ((opts === null || opts === void 0 ? void 0 : opts.languageCharacters) || []).map(function (config) {
    return (0, _characters["default"])(_objectSpread(_objectSpread({}, config), {}, {
      keyPadCharacterRef: opts.keyPadCharacterRef,
      setKeypadInteraction: opts.setKeypadInteraction
    }));
  });
  var tablePlugins = [imagePlugin, mathPlugin, respAreaPlugin].concat((0, _toConsumableArray2["default"])(languageCharactersPlugins));

  if (opts.responseArea && opts.responseArea.type === 'math-templated') {
    tablePlugins.push(respAreaPlugin);
  }

  var builtCustomPlugins = [];
  customPlugins.forEach(function (customPlugin) {
    var _ref2 = customPlugin || {},
        event = _ref2.event,
        icon = _ref2.icon,
        iconType = _ref2.iconType,
        iconAlt = _ref2.iconAlt;

    function isValidEventName(eventName) {
      // Check if eventName is a non-empty string
      if (typeof eventName !== 'string' || eventName.length === 0) {
        return false;
      } // Regular expression to match valid event names (only alphanumeric characters and underscore)


      var regex = /^[a-zA-Z0-9_]+$/; // Check if the eventName matches the regular expression

      return regex.test(eventName);
    }

    if (!isValidEventName(event)) {
      console.error("The event name: ".concat(event, " is not a valid event name!"));
      return;
    }

    if (!icon && !iconType && !iconAlt) {
      console.error('Your custom button requires icon, iconType and iconAlt');
      return;
    }

    builtCustomPlugins.push((0, _customPlugin["default"])('custom-plugin', customPlugin));
  });
  return (0, _compact["default"])([addIf('table', (0, _table["default"])(opts.table, (0, _compact["default"])(tablePlugins))), addIf('bold', MarkHotkey({
    key: 'b',
    type: 'bold',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatBold["default"], null),
    tag: 'strong'
  })), // addIf('code', MarkHotkey({ key: '`', type: 'code', icon: <Code /> })),
  addIf('italic', MarkHotkey({
    key: 'i',
    type: 'italic',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatItalic["default"], null),
    tag: 'em'
  })), addIf('strikethrough', MarkHotkey({
    key: '~',
    type: 'strikethrough',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatStrikethrough["default"], null),
    tag: 'del'
  })), addIf('underline', MarkHotkey({
    key: 'u',
    type: 'underline',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatUnderlined["default"], null),
    tag: 'u'
  })), // icon should be modifies accordingly
  addIf('superscript', MarkHotkey({
    type: 'sup',
    icon: /*#__PURE__*/_react["default"].createElement(SuperscriptIcon, null),
    tag: 'sup'
  })), // icon should be modifies accordingly
  addIf('subscript', MarkHotkey({
    type: 'sub',
    icon: /*#__PURE__*/_react["default"].createElement(SubscriptIcon, null),
    tag: 'sub'
  })), addIf('image', imagePlugin), addIf('video', (0, _media["default"])('video', opts.media)), addIf('audio', (0, _media["default"])('audio', opts.media)), addIf('math', mathPlugin)].concat((0, _toConsumableArray2["default"])(languageCharactersPlugins.map(function (plugin) {
    return addIf('languageCharacters', plugin);
  })), [addIf('text-align', (0, _textAlign["default"])(opts.textAlign)), addIf('blockquote', MarkHotkey({
    key: 'q',
    type: 'blockquote',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatQuote["default"], null),
    tag: 'blockquote'
  })), addIf('h3', MarkHotkey({
    key: 'h3',
    type: 'h3',
    icon: /*#__PURE__*/_react["default"].createElement(HeadingIcon, null),
    tag: 'h3'
  })), addIf('bulleted-list', (0, _list["default"])({
    key: 'l',
    type: 'ul_list',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatListBulleted["default"], null)
  })), addIf('numbered-list', (0, _list["default"])({
    key: 'n',
    type: 'ol_list',
    icon: /*#__PURE__*/_react["default"].createElement(_FormatListNumbered["default"], null)
  })), addIf('undo', UndoRedo('undo')), addIf('redo', UndoRedo('redo')), (0, _toolbar["default"])(opts.toolbar), (0, _slateSoftBreak["default"])({
    shift: true
  })], builtCustomPlugins, [addIf('responseArea', respAreaPlugin), cssPlugin, addIf('html', (0, _html["default"])(opts.html)), EnterHandlingPlugin(), (0, _rendering["default"])()]));
};

exports.buildPlugins = buildPlugins;
//# sourceMappingURL=index.js.map