"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCustomStyleCommands = getCustomStyleCommands;
exports.updateOverrideFlag = updateOverrideFlag;
exports.getMarkByStyleName = getMarkByStyleName;
exports.executeCommands = executeCommands;
exports.applyLatestStyle = applyLatestStyle;
exports.applyStyle = applyStyle;
exports.getNode = getNode;
exports.default = exports.BOLDPARTIAL = exports.LEVEL = exports.LEVELBASEDINDENT = exports.NUMBERING = exports.INDENT = exports.ATTR_OVERRIDDEN = exports.SBEFORE = exports.SAFTER = exports.NONE = exports.LHEIGHT = exports.ALIGN = exports.UNDERLINE = exports.TEXTHL = exports.SUPER = exports.STRIKE = exports.FONTNAME = exports.FONTSIZE = exports.COLOR = exports.EM = exports.STRONG = void 0;

var _prosemirrorState = require("prosemirror-state");

var _prosemirrorTransform = require("prosemirror-transform");

var _prosemirrorView = require("prosemirror-view");

var _prosemirrorModel = require("prosemirror-model");

var _UICommand = _interopRequireDefault(require("./ui/UICommand"));

var _PopUpPosition = require("./ui/PopUpPosition");

var _createPopUp = _interopRequireDefault(require("./ui/createPopUp"));

var _CustomStyleEditor = _interopRequireDefault(require("./ui/CustomStyleEditor"));

var _MarkToggleCommand = _interopRequireDefault(require("./MarkToggleCommand"));

var _TextColorCommand = _interopRequireDefault(require("./TextColorCommand"));

var _TextHighlightCommand = _interopRequireDefault(require("./TextHighlightCommand"));

var _TextAlignCommand = _interopRequireWildcard(require("./TextAlignCommand"));

var _FontTypeCommand = _interopRequireDefault(require("./FontTypeCommand"));

var _FontSizeCommand = _interopRequireDefault(require("./FontSizeCommand"));

var _TextLineSpacingCommand = _interopRequireDefault(require("./TextLineSpacingCommand"));

var _ParagraphSpacingCommand = _interopRequireDefault(require("./ParagraphSpacingCommand"));

var _IndentCommand = _interopRequireDefault(require("./IndentCommand"));

var _clearCustomStyleMarks = require("./clearCustomStyleMarks");

var _customStyle = require("./customStyle");

var _MarkNames = require("./MarkNames");

var _NodeNames = require("./NodeNames");

var _toCSSLineSpacing = require("./ui/toCSSLineSpacing");

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

const STRONG = 'strong';
exports.STRONG = STRONG;
const EM = 'em';
exports.EM = EM;
const COLOR = 'color';
exports.COLOR = COLOR;
const FONTSIZE = 'fontSize';
exports.FONTSIZE = FONTSIZE;
const FONTNAME = 'fontName';
exports.FONTNAME = FONTNAME;
const STRIKE = 'strike';
exports.STRIKE = STRIKE;
const SUPER = 'super';
exports.SUPER = SUPER;
const TEXTHL = 'textHighlight';
exports.TEXTHL = TEXTHL;
const UNDERLINE = 'underline';
exports.UNDERLINE = UNDERLINE;
const ALIGN = 'align';
exports.ALIGN = ALIGN;
const LHEIGHT = 'lineHeight';
exports.LHEIGHT = LHEIGHT;
const NONE = 'None';
exports.NONE = NONE;
const SAFTER = 'paragraphSpacingAfter';
exports.SAFTER = SAFTER;
const SBEFORE = 'paragraphSpacingBefore';
exports.SBEFORE = SBEFORE;
const ATTR_OVERRIDDEN = 'overridden';
exports.ATTR_OVERRIDDEN = ATTR_OVERRIDDEN;
const INDENT = 'indent';
exports.INDENT = INDENT;
const NUMBERING = 'hasNumbering';
exports.NUMBERING = NUMBERING;
const LEVELBASEDINDENT = 'isLevelbased';
exports.LEVELBASEDINDENT = LEVELBASEDINDENT;
const LEVEL = 'styleLevel';
exports.LEVEL = LEVEL;
const BOLDPARTIAL = 'boldPartial'; // [FS] IRAD-1042 2020-10-01
// Creates commands based on custom style JSon object

exports.BOLDPARTIAL = BOLDPARTIAL;

function getCustomStyleCommands(customStyle) {
  const commands = [];

  for (const property in customStyle) {
    switch (property) {
      case STRONG:
        // [FS] IRAD-1043 2020-10-23
        // Issue fix : unselect a style when creating a new style
        // and that unselected styles also applied in selected paragraph
        if (customStyle[property]) commands.push(new _MarkToggleCommand.default('strong'));
        break;

      case EM:
        // [FS] IRAD-1043 2020-10-23
        // Issue fix : unselect a style when creating a new style
        // and that unselected styles also applied in selected paragrapgh
        if (customStyle[property]) commands.push(new _MarkToggleCommand.default('em'));
        break;

      case COLOR:
        commands.push(new _TextColorCommand.default(customStyle[property]));
        break;

      case FONTSIZE:
        commands.push(new _FontSizeCommand.default(Number(customStyle[property])));
        break;

      case FONTNAME:
        commands.push(new _FontTypeCommand.default(customStyle[property]));
        break;

      case STRIKE:
        // [FS] IRAD-1043 2020-10-23
        // Issue fix : unselect a style when creating a new style
        // and that unselected styles also applied in selected paragrapgh
        if (customStyle[property]) commands.push(new _MarkToggleCommand.default('strike'));
        break;

      case SUPER:
        commands.push(new _MarkToggleCommand.default('super'));
        break;

      case TEXTHL:
        commands.push(new _TextHighlightCommand.default(customStyle[property]));
        break;

      case UNDERLINE:
        // [FS] IRAD-1043 2020-12-15
        // Issue fix: user unselect Underline from a existing custom style, it didn't reflect in editor
        if (customStyle[property]) commands.push(new _MarkToggleCommand.default('underline'));
        break;

      case ALIGN:
        commands.push(new _TextAlignCommand.default(customStyle[property]));
        break;

      case LHEIGHT:
        commands.push(new _TextLineSpacingCommand.default(customStyle[property]));
        break;
      // [FS] IRAD-1100 2020-11-05
      // Add in leading and trailing spacing (before and after a paragraph)

      case SAFTER:
        commands.push(new _ParagraphSpacingCommand.default(customStyle[property], true));
        break;

      case SBEFORE:
        commands.push(new _ParagraphSpacingCommand.default(customStyle[property], false));
        break;

      case INDENT:
        if (0 < customStyle[property]) {
          commands.push(new _IndentCommand.default(customStyle[property]));
        }

        break;

      case LEVELBASEDINDENT:
        // [FS] IRAD-1162 2021-1-25
        // Bug fix: indent not working along with level
        if (customStyle[LEVEL] && Number(customStyle[LEVEL]) > 0) {
          commands.push(new _IndentCommand.default(customStyle[LEVEL]));
        }

        break;

      default:
        break;
    }
  }

  return commands;
}

class CustomStyleCommand extends _UICommand.default {
  constructor(customStyle, customStyleName) {
    super();

    _defineProperty(this, "_customStyleName", void 0);

    _defineProperty(this, "_customStyle", []);

    _defineProperty(this, "_popUp", null);

    _defineProperty(this, "renderLabel", state => {
      return this._customStyleName;
    });

    _defineProperty(this, "getTheInlineStyles", isInline => {
      let attrs = {};
      let propsCopy = [];
      propsCopy = Object.assign(propsCopy, this._customStyle);
      propsCopy.forEach(style => {
        attrs = Object.assign(attrs, style);
        Object.entries(style).forEach((_ref) => {
          let [key, value] = _ref;

          if (isInline && typeof value === 'boolean') {
            delete attrs[key];
          } else if (!isInline && typeof value != 'boolean') {
            delete attrs[key];
          }
        });
      });
      return attrs;
    });

    _defineProperty(this, "isEmpty", obj => {
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }

      return true;
    });

    _defineProperty(this, "isEnabled", (state, view, menuTitle) => {
      // [FS] IRAD-1053 2020-10-22
      // Disable the Clear style menu when no styles applied to a paragraph
      return !('clearstyle' == menuTitle && NONE == this.isCustomStyleApplied(state));
    });

    _defineProperty(this, "execute", (state, dispatch, view) => {
      let {
        tr
      } = state;
      const {
        selection
      } = state;

      if ('newstyle' === this._customStyle) {
        this.editWindow(state, view);
        return false;
      } // [FS] IRAD-1053 2020-10-08
      // to remove the custom styles applied in the selected paragraph
      else if ('clearstyle' === this._customStyle || 'None' === this._customStyle) {
          tr = this.clearCustomStyles(state.tr.setSelection(selection), state);
          tr = (0, _clearCustomStyleMarks.removeTextAlignAndLineSpacing)(tr, state.schema);
          const startPos = selection.$from.before(1);
          const endPos = selection.$to.after(1);
          const node = getNode(state, startPos, endPos, tr);
          const newattrs = Object.assign({}, node.attrs);
          tr = createEmptyElement(state, tr, node, startPos, endPos, newattrs);

          if (dispatch && tr.docChanged) {
            dispatch(tr);
            return true;
          }

          return false;
        }

      tr = applyStyle(this._customStyle.styles, this._customStyle.styleName, state, tr);

      if (tr.docChanged || tr.storedMarksSet) {
        // view.focus();
        dispatch && dispatch(tr);
        return true;
      }

      return false;
    });

    this._customStyle = customStyle;
    this._customStyleName = customStyleName;
  }

  // [FS] IRAD-1053 2020-10-22
  // returns the applied style of a paragraph
  isCustomStyleApplied(editorState) {
    const {
      selection,
      doc
    } = editorState;
    const {
      from,
      to
    } = selection;
    let customStyleName = NONE;
    doc.nodesBetween(from, to, (node, pos) => {
      if (node.attrs.styleName) {
        customStyleName = node.attrs.styleName;
      }
    });
    return customStyleName;
  }

  // [FS] IRAD-1053 2020-12-17
  // to clear the custom styles in the selected paragrapgh
  clearCustomStyles(tr, editorState) {
    const {
      selection,
      doc
    } = editorState;
    const {
      from,
      to
    } = selection;
    let customStyleName = NONE;
    doc.nodesBetween(from, to, (node, pos) => {
      if (node.attrs.styleName) {
        customStyleName = node.attrs.styleName;
        const storedmarks = getMarkByStyleName(customStyleName, editorState.schema);
        tr = this.removeMarks(storedmarks, tr, node);
        return tr;
      }

      return tr;
    });
    return tr;
  }

  removeMarks(marks, tr, node) {
    const {
      selection
    } = tr;
    let {
      from,
      to
    } = selection;
    const {
      empty
    } = selection;

    if (empty) {
      from = selection.$from.before(1);
      to = selection.$to.after(1);
    } // reset the custom style name to NONE after remove the styles


    (0, _clearCustomStyleMarks.clearCustomStyleAttribute)(node);
    marks.forEach(mark => {
      tr = tr.removeMark(from, to, mark.type);
    });
    return tr;
  } // shows the create style popup


  editWindow(state, view) {
    const {
      dispatch
    } = view;
    let tr = state.tr;
    const doc = state.doc;
    this._popUp = (0, _createPopUp.default)(_CustomStyleEditor.default, this.createCustomObject(), {
      autoDismiss: false,
      position: _PopUpPosition.atViewportCenter,
      onClose: val => {
        if (this._popUp) {
          this._popUp = null; //handle save style object part here

          if (undefined !== val) {
            this.saveStyleObject(val);
            tr = tr.setSelection(_prosemirrorState.TextSelection.create(doc, 0, 0)); // Apply created styles to document

            tr = applyStyle(val.styles, val.styleName, state, tr);
            dispatch(tr); // view.focus();
          }
        }
      }
    });
  } // creates a sample style object


  createCustomObject() {
    return {
      styleName: '',
      mode: 0,
      //new
      styles: {}
    };
  } // locally save style object


  saveStyleObject(style) {
    (0, _customStyle.saveStyle)(style);
  }

}

function compareMarkWithStyle(mark, style, tr, startPos, endPos, retObj) {
  let same = false;
  let overridden = false;

  switch (mark.type.name) {
    case _MarkNames.MARK_STRONG:
      same = undefined != style[STRONG];
      break;

    case _MarkNames.MARK_EM:
      same = undefined != style[EM];
      break;

    case _MarkNames.MARK_TEXT_COLOR:
      same = mark.attrs['color'] == style[COLOR];
      break;

    case _MarkNames.MARK_FONT_SIZE:
      same = mark.attrs['pt'] == style[FONTSIZE];
      break;

    case _MarkNames.MARK_FONT_TYPE:
      same = mark.attrs['name'] == style[FONTNAME];
      break;

    case _MarkNames.MARK_STRIKE:
      same = undefined != style[STRIKE];
      break;

    case _MarkNames.MARK_SUPER:
      break;

    case _MarkNames.MARK_TEXT_HIGHLIGHT:
      break;

    case _MarkNames.MARK_UNDERLINE:
      same = undefined != style[UNDERLINE];
      break;

    default:
      break;
  }

  overridden = !same;

  if (undefined != mark.attrs[ATTR_OVERRIDDEN] && mark.attrs[ATTR_OVERRIDDEN] != overridden && tr.curSelection) {
    mark.attrs[ATTR_OVERRIDDEN] = overridden;
    tr = tr.removeMark(startPos, endPos, mark);
    tr = tr.addMark(startPos, endPos, mark);
    retObj.modified = true;
  }
  /*
    case SUPER:
    case TEXTHL:
    case ALIGN:
    case LHEIGHT:*/


  return tr;
}

function updateOverrideFlag(styleName, tr, node, startPos, endPos, retObj) {
  const style = (0, _customStyle.getCustomStyleByName)(styleName);

  if (style) {
    node.descendants(function (child, pos, parent) {
      if (child instanceof _prosemirrorModel.Node) {
        child.marks.forEach(function (mark, index) {
          tr = compareMarkWithStyle(mark, style, tr, startPos, endPos, retObj);
        });
      }
    });
  }

  return tr;
}

function onLoadRemoveAllMarksExceptOverridden(node, schema, from, to, tr) {
  const tasks = [];
  node.descendants(function (child, pos, parent) {
    if (child instanceof _prosemirrorModel.Node) {
      child.marks.forEach(function (mark, index) {
        if (!mark.attrs[ATTR_OVERRIDDEN]) {
          tasks.push({
            child,
            pos,
            mark
          });
        }
      });
    }
  });
  return handleRemoveMarks(tr, tasks, from, to, schema);
}

function getMarkByStyleName(styleName, schema) {
  const style = (0, _customStyle.getCustomStyleByName)(styleName);
  const marks = [];
  let markType = null;
  let attrs = null;

  for (const property in style) {
    switch (property) {
      case STRONG:
      case BOLDPARTIAL:
        if (style[property]) {
          markType = schema.marks[_MarkNames.MARK_STRONG];
          marks.push(markType.create(attrs));
        }

        break;

      case EM:
        markType = schema.marks[_MarkNames.MARK_EM];
        if (style[property]) marks.push(markType.create(attrs));
        break;

      case COLOR:
        markType = schema.marks[_MarkNames.MARK_TEXT_COLOR];
        attrs = style[property] ? {
          color: style[property]
        } : null;
        marks.push(markType.create(attrs));
        break;

      case FONTSIZE:
        markType = schema.marks[_MarkNames.MARK_FONT_SIZE];
        attrs = style[property] ? {
          pt: style[property]
        } : null;
        marks.push(markType.create(attrs));
        break;

      case FONTNAME:
        markType = schema.marks[_MarkNames.MARK_FONT_TYPE];
        attrs = style[property] ? {
          name: style[property]
        } : null;
        marks.push(markType.create(attrs));
        break;

      case TEXTHL:
        markType = schema.marks[_MarkNames.MARK_TEXT_HIGHLIGHT];
        attrs = style[property] ? {
          highlightColor: style[property]
        } : null;
        marks.push(markType.create(attrs));
        break;

      case UNDERLINE:
        markType = schema.marks[_MarkNames.MARK_UNDERLINE];
        marks.push(markType.create(attrs));
        break;

      default:
        break;
    }
  }

  return marks;
}

function applyStyleEx(style, styleName, state, tr, node, startPos, endPos) {
  const loading = !style;

  if (loading) {
    style = (0, _customStyle.getCustomStyleByName)(styleName);
  }

  const _commands = getCustomStyleCommands(style);

  if (loading) {
    tr = onLoadRemoveAllMarksExceptOverridden(node, state.schema, startPos, endPos, tr);
  } else {
    // [FS] IRAD-1087 2020-11-02
    // Issue fix: applied link is missing after applying a custom style.
    tr = removeAllMarksExceptLink(startPos, endPos, tr, state.schema);
  }

  const newattrs = Object.assign({}, node.attrs); // [FS] IRAD-1074 2020-10-22
  // Issue fix on not removing center alignment when switch style with center
  // alignment to style with left alignment

  newattrs['align'] = null;
  newattrs['lineSpacing'] = null;
  newattrs['paragraphSpacingAfter'] = null;
  newattrs['paragraphSpacingBefore'] = null; // [FS] IRAD-1131 2021-01-12
  // Indent overriding not working on a paragraph where cussom style is applied

  newattrs['indent'] = null;
  newattrs['styleName'] = styleName;

  _commands.forEach(element => {
    // to set the node attribute for text-align
    if (element instanceof _TextAlignCommand.default) {
      newattrs['align'] = style.align; // to set the node attribute for line-height
    } else if (element instanceof _TextLineSpacingCommand.default) {
      // [FS] IRAD-1104 2020-11-13
      // Issue fix : Linespacing Double and Single not applied in the sample text paragrapgh
      newattrs['lineSpacing'] = (0, _toCSSLineSpacing.getLineSpacingValue)(style.lineHeight);
    } else if (element instanceof _ParagraphSpacingCommand.default) {
      // [FS] IRAD-1100 2020-11-05
      // Add in leading and trailing spacing (before and after a paragraph)
      newattrs['paragraphSpacingAfter'] = style.paragraphSpacingAfter ? style.paragraphSpacingAfter : null;
      newattrs['paragraphSpacingBefore'] = style.paragraphSpacingBefore ? style.paragraphSpacingBefore : null;
    } else if (element instanceof _IndentCommand.default) {
      // [FS] IRAD-1162 2021-1-25
      // Bug fix: indent not working along with level
      newattrs['indent'] = style.isLevelbased ? style.styleLevel : style.indent;
    } // to set the marks for the node


    if (typeof element.executeCustom == 'function') {
      tr = element.executeCustom(state, tr, startPos, endPos);
    }
  });

  if (style && style[NUMBERING]) {
    newattrs['styleLevel'] = Number(style.styleLevel);
    newattrs['customStyle'] = {
      strong: style[STRONG],
      em: style[EM],
      color: style[COLOR],
      fontSize: style[FONTSIZE],
      fontName: style[FONTNAME],
      strike: style[STRIKE],
      underline: style[UNDERLINE],
      boldNumbering: style['boldNumbering']
    };
  } else {
    newattrs['styleLevel'] = null;
  } // to set custom styleName attribute for node


  newattrs['styleName'] = styleName;
  tr = applyLineStyle(node, style, state, tr, startPos);
  const storedmarks = getMarkByStyleName(styleName, state.schema);
  tr = _setNodeAttribute(state, tr, startPos, endPos, newattrs);
  tr = createEmptyElement(state, tr, node, startPos, endPos, newattrs);
  tr.storedMarks = storedmarks;
  return tr;
}

function createEmptyElement(state, tr, node, startPos, endPos, attrs) {
  const currentLevel = node.attrs.styleLevel;
  let previousLevel = null;
  let levelDiff = 0;
  let nextLevel = null;
  const nodesBeforeSelection = [];
  let nodesAfterSelection = null;
  const docSize = tr.doc.nodeSize - 2; // Manage heirachy for nodes of previous  position

  if (startPos !== 0) {
    // Fix: document Load Error- Instead of state doc here give transaction doc,because when we apply changes
    // dynamically through transactions the node position  get affected,
    // so depending on state doc nodes' positions is incorrect.
    tr.doc.descendants((node, pos) => {
      if (isAllowedNode(node)) {
        if (pos >= startPos) {
          return false;
        }

        nodesBeforeSelection.push({
          pos,
          node
        });
      }

      return true;
    });
    nodesBeforeSelection.reverse();
    nodesBeforeSelection.every(item => {
      if (null !== item.node.attrs.styleLevel) {
        previousLevel = item.node.attrs.styleLevel;
        return false;
      }

      return true;
    });

    if (null === previousLevel && null == currentLevel) {
      if (attrs.styleLevel !== 1) {
        tr = addElement(attrs, state, tr, startPos, null);
      }
    } else {
      levelDiff = previousLevel ? attrs.styleLevel - previousLevel : attrs.styleLevel;

      if (levelDiff > 1) {
        tr = addElement(attrs, state, tr, startPos, previousLevel);
      }

      if (levelDiff < 0) {
        tr = addElement(attrs, state, tr, startPos, previousLevel);
      }
    }
  } else {
    if (attrs.styleLevel !== 1) {
      tr = addElement(attrs, state, tr, startPos, null);
    }
  } // Manage heirachy for nodes of next position


  if (docSize > endPos) {
    // Fix: document Load Error -Instead of state doc here give transaction doc,because when we apply changes
    // dynamically through transactions the node position  get affected,
    // so depending on state doc nodes' positions is incorrect.
    tr.doc.nodesBetween(endPos, docSize, (node, pos) => {
      if (isAllowedNode(node) && node.attrs.styleLevel && null === nodesAfterSelection) {
        nodesAfterSelection = node;
        return false;
      }

      return true;
    });
  }

  if (null !== nodesAfterSelection) {
    const selectedLevel = attrs.styleLevel ? attrs.styleLevel : 0;
    nextLevel = nodesAfterSelection.attrs.styleLevel;
    levelDiff = nextLevel - selectedLevel;

    if (nextLevel === attrs.styleLevel || levelDiff === 1) {
      return tr;
    } else {
      tr = addElementAfter(attrs, state, tr, endPos, nextLevel);
    }
  }

  return tr;
}

function addElement(nodeAttrs, state, tr, startPos, previousLevel) {
  const level = nodeAttrs.styleLevel ? nodeAttrs.styleLevel - 1 : 0;
  const counter = previousLevel ? previousLevel : 0;
  const paragraph = state.schema.nodes[_NodeNames.PARAGRAPH];

  for (let index = level; index > counter; index--) {
    nodeAttrs.styleLevel = index;
    nodeAttrs.styleName = 'None';
    nodeAttrs.customStyle = null;
    const paragraphNode = paragraph.create(nodeAttrs, null, null);
    tr = tr.insert(startPos, _prosemirrorModel.Fragment.from(paragraphNode));
  }

  return tr;
}

function addElementAfter(nodeAttrs, state, tr, startPos, nextLevel) {
  const counter = nodeAttrs.styleLevel ? nodeAttrs.styleLevel : 1;
  const level = nextLevel ? nextLevel - 1 : 0;
  const paragraph = state.schema.nodes[_NodeNames.PARAGRAPH];

  for (let index = level; index > counter; index--) {
    nodeAttrs.styleLevel = index;
    nodeAttrs.styleName = 'None';
    nodeAttrs.customStyle = null;
    const paragraphNode = paragraph.create(nodeAttrs, null, null);
    tr = tr.insert(startPos, _prosemirrorModel.Fragment.from(paragraphNode));
  }

  if (level === counter) {
    nodeAttrs.styleLevel = 1;
    nodeAttrs.styleName = 'None';
    nodeAttrs.customStyle = null;
    const paragraphNode = paragraph.create(nodeAttrs, null, null);
    tr = tr.insert(startPos, _prosemirrorModel.Fragment.from(paragraphNode));
  }

  return tr;
}

function applyLineStyle(node, style, state, tr, startPos) {
  if (style && style.boldPartial) {
    let textContent = '';
    const markType = state.schema.marks[_MarkNames.MARK_STRONG];

    if (style.boldSentence) {
      node.descendants(function (child, pos, parent) {
        if ('text' === child.type.name) {
          textContent = `${textContent}${child.text}`;
        }
      });
      textContent = textContent.split('.')[0];
      tr = tr.addMark(startPos, startPos + textContent.length + 1, markType.create(null));
    } else {
      node.descendants(function (child, pos, parent) {
        if ('text' === child.type.name) {
          textContent = `${textContent}${child.text}`;
        }
      });
      textContent = textContent.split(' ')[0];
      tr = tr.addMark(startPos, startPos + textContent.length + 1, markType.create(null));
    }
  }

  return tr;
}

function executeCommands(state, tr, styleName, startPos, endPos) {
  const style = (0, _customStyle.getCustomStyleByName)(styleName);

  const _commands = getCustomStyleCommands(style);

  _commands.forEach(element => {
    if (typeof element.executeCustom == 'function') {
      tr = element.executeCustom(state, tr, startPos, endPos);
    }
  });

  return tr;
} // Need to change this function code duplicates with applyStyle()


function applyLatestStyle(styleName, state, tr, node, startPos, endPos) {
  let style = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null;
  return applyStyleEx(style, styleName, state, tr, node, startPos, endPos);
}

function isAllowedNode(node) {
  return node.type.name === 'paragraph';
} // [FS] IRAD-1088 2020-10-05
// set custom style for node


function _setNodeAttribute(state, tr, from, to, attribute) {
  tr.doc.nodesBetween(from, to, (node, startPos) => {
    if (isAllowedNode(node)) {
      tr = tr.setNodeMarkup(startPos, undefined, attribute);
    }
  });
  return tr;
} // [FS] IRAD-1087 2020-11-02
// Issue fix: Missing the applied link after applying a style


function removeAllMarksExceptLink(from, to, tr, schema) {
  const {
    doc
  } = tr;
  const tasks = [];
  doc.nodesBetween(from, to, (node, pos) => {
    if (node.marks && node.marks.length) {
      node.marks.some(mark => {
        if ('link' !== mark.type.name) {
          tasks.push({
            node,
            pos,
            mark
          });
        }
      });
      return true;
    }

    return true;
  });
  return handleRemoveMarks(tr, tasks, from, to, schema);
}

function handleRemoveMarks(tr, tasks, from, to, schema) {
  tasks.forEach(job => {
    const {
      mark
    } = job;
    tr = tr.removeMark(from, to, mark.type);
  });
  tr = (0, _TextAlignCommand.setTextAlign)(tr, schema, null);
  return tr;
} // [FS] IRAD-1087 2020-10-14
// Apply selected styles to document


function applyStyle(style, styleName, state, tr) {
  const {
    selection
  } = state;
  const startPos = selection.$from.before(1);
  const endPos = selection.$to.after(1);
  const node = getNode(state, startPos, endPos, tr);
  return applyStyleEx(style, styleName, state, tr, node, startPos, endPos);
} //to get the selected node


function getNode(state, from, to, tr) {
  let selectedNode = null;
  tr.doc.nodesBetween(from, to, (node, startPos) => {
    if (node.type.name === 'paragraph') {
      selectedNode = node;
    }
  });
  return selectedNode;
}

var _default = CustomStyleCommand;
exports.default = _default;