import { isNullOrUndefined as isNOU, detach, createElement, addClass, updateCSSText } from '@syncfusion/ej2-base';
var UPPER_ALPHA = 'upper-alpha';
var UPPER_ROMAN = 'upper-roman';
var LOWER_ROMAN = 'lower-roman';
var LOWER_GREEK = 'lower-greek';
var LOWER_ALPHA = 'lower-alpha';
var DECIMAL_LD_ZERO = 'decimal-leading-zero';
var DECIMAL = 'decimal';
var CIRCLE = 'circle';
var SQUARE = 'square';
var DISC = 'disc';
/**
 * Handles cleanup of pasted content for the Block Editor.
 */
var ClipboardCleanupModule = /** @class */ (function () {
    function ClipboardCleanupModule(manager) {
        this.listContents = [];
        this.parent = manager;
    }
    /**
     * Handles the paste cleanup process.
     * It checks if the paste content is plain text or from MS Word and processes accordingly.
     *
     * @param {IPasteCleanupOptions} args - The arguments for paste cleanup.
     * @returns {string} - The cleaned HTML content.
     * @hidden
     */
    ClipboardCleanupModule.prototype.cleanupPaste = function (args) {
        var html = args.html, plainText = args.plainText;
        if (this.parent.pasteCleanupSettings.plainText) {
            return this.plainFormatting(plainText);
        }
        var isFromMsWord = this.isFromMsWord(html);
        if (isFromMsWord) {
            return this.cleanMsWordContent(html);
        }
        return this.cleanupHtml(html, this.parent.pasteCleanupSettings.keepFormat);
    };
    ClipboardCleanupModule.prototype.isFromMsWord = function (html) {
        return ClipboardCleanupModule.msWordPatterns.some(function (pattern) { return pattern.test(html); });
    };
    ClipboardCleanupModule.prototype.cleanMsWordContent = function (html) {
        var tempDiv = createElement('div');
        tempDiv.innerHTML = html;
        var listNodes = [];
        this.addListClass(tempDiv);
        listNodes = this.cleanUp(tempDiv, listNodes);
        if (!isNOU(listNodes[0]) && listNodes[0].parentElement.tagName !== 'UL' &&
            listNodes[0].parentElement.tagName !== 'OL') {
            this.listConverter(listNodes);
        }
        // Remove Word-specific elements
        this.removeUnwantedElements(tempDiv);
        // Clean up lists
        this.cleanupLists(tempDiv);
        // Process tables
        this.processTables(tempDiv);
        // Remove Word-specific classes
        this.removeWordClasses(tempDiv);
        // Clean up styles
        this.cleanupStyles(tempDiv, this.parent.pasteCleanupSettings.allowedStyles);
        // Remove empty elements
        this.removeEmptyElements(tempDiv);
        // Remove comments
        this.removeComments(tempDiv);
        // Process images
        this.processImages(tempDiv);
        return tempDiv.innerHTML;
    };
    ClipboardCleanupModule.prototype.addListClass = function (elm) {
        var allNodes = elm.querySelectorAll('*');
        for (var index = 0; index < allNodes.length; index++) {
            if (!isNOU(allNodes[index].getAttribute('style')) && allNodes[index].getAttribute('style').replace(/ /g, '').replace('\n', '').indexOf('mso-list:l') >= 0 &&
                allNodes[index].className.toLowerCase().indexOf('msolistparagraph') === -1 &&
                allNodes[index].tagName.charAt(0) !== 'H' && allNodes[index].tagName !== 'LI' &&
                allNodes[index].tagName !== 'OL' && allNodes[index].tagName !== 'UL') {
                allNodes[index].classList.add('msolistparagraph');
            }
        }
    };
    ClipboardCleanupModule.prototype.cleanUp = function (node, listNodes) {
        var tempCleaner = [];
        var prevflagState;
        var allNodes = node.querySelectorAll('*');
        for (var index = 0; index < allNodes.length; index++) {
            if (ClipboardCleanupModule.ignorableNodes.indexOf(allNodes[index].nodeName) === -1 ||
                (allNodes[index].nodeType === 3 && allNodes[index].textContent.trim() === '')) {
                tempCleaner.push(allNodes[index]);
                continue;
            }
            else if (allNodes[index].className &&
                allNodes[index].className.toLowerCase().indexOf('msolistparagraph') !== -1 &&
                !isNOU(allNodes[index].getAttribute('style')) &&
                allNodes[index].getAttribute('style').indexOf('mso-list:') >= 0) {
                if (allNodes[index].className.indexOf('MsoListParagraphCxSpFirst') >= 0 && listNodes.length > 0 &&
                    listNodes[listNodes.length - 1] !== null) {
                    listNodes.push(null);
                }
                listNodes.push(allNodes[index]);
            }
            if (prevflagState && (ClipboardCleanupModule.blockNode.indexOf(allNodes[index].nodeName.toLowerCase()) !== -1) &&
                !(allNodes[index].className &&
                    allNodes[index].className.toLowerCase().indexOf('msolistparagraph') !== -1 && !isNOU(allNodes[index].getAttribute('style')) &&
                    allNodes[index].getAttribute('style').indexOf('mso-list:') >= 0)) {
                listNodes.push(null);
            }
            if (ClipboardCleanupModule.blockNode.indexOf(allNodes[index].nodeName.toLowerCase()) !== -1) {
                if (allNodes[index].className &&
                    allNodes[index].className.toLowerCase().indexOf('msolistparagraph') !== -1 && !isNOU(allNodes[index].getAttribute('style')) &&
                    allNodes[index].getAttribute('style').indexOf('mso-list:') >= 0) {
                    prevflagState = true;
                }
                else {
                    prevflagState = false;
                }
            }
        }
        if (listNodes.length && (listNodes[listNodes.length - 1] !== null)) {
            listNodes.push(null);
        }
        return listNodes;
    };
    ClipboardCleanupModule.prototype.listConverter = function (listNodes) {
        var level;
        var data = [];
        var listFormatOverride;
        var collection = [];
        var content = '';
        var stNode;
        var currentListStyle = '';
        for (var i = 0; i < listNodes.length; i++) {
            if (listNodes[i] === null) {
                data.push({ content: this.makeConversion(collection), node: listNodes[i - 1] });
                collection = [];
                continue;
            }
            if (listNodes[i].getAttribute('style') && listNodes[i].getAttribute('style').indexOf('mso-outline-level') !== -1) {
                listNodes[i].setAttribute('style', listNodes[i].getAttribute('style').replace('mso-outline-level', 'mso-outline'));
            }
            content = listNodes[i].getAttribute('style');
            if (content && content.indexOf('level') !== -1) {
                level = parseInt(content.charAt(content.indexOf('level') + 5), 10);
            }
            else {
                level = 1;
            }
            if (content && content.indexOf('mso-list:') !== -1) {
                var msoListValue = void 0;
                if (content.match(/mso-list:[^;]+;?/)) {
                    var changedContent = content.replace(new RegExp('\\n', 'g'), '').split(' ').join('');
                    msoListValue = changedContent.match(/mso-list:[^;]+;?/)[0].split(':l');
                    listFormatOverride = isNOU(msoListValue) ? null : parseInt(msoListValue[1].split('level')[0], 10);
                }
                else {
                    listFormatOverride = null;
                }
            }
            this.listContents = [];
            this.getListContent(listNodes[i]);
            var type = void 0;
            var listStyleType = void 0;
            var startAttr = void 0;
            var styleMarginLeft = void 0;
            if (!isNOU(this.listContents[0])) {
                type = this.listContents[0].trim().length > 1 ? 'ol' : 'ul';
                listStyleType = this.getlistStyleType(this.listContents[0], type);
                if (type === 'ol' && (i === 0 || listNodes[i - 1] === null)) {
                    var startString = this.listContents[0].split('.')[0];
                    var listTypes = ['A', 'a', 'I', 'i', 'α', '1', '01', '1-']; // Add '1-' for rare list type.
                    if (listTypes.indexOf(startString) === -1) {
                        if (listStyleType === DECIMAL) {
                            if (!isNaN(parseInt(startString, 10))) {
                                startAttr = parseInt(startString, 10);
                            }
                        }
                        else if (listStyleType === DECIMAL_LD_ZERO) {
                            if (!isNaN(parseInt(startString, 10))) {
                                startAttr = parseInt(startString, 10);
                            }
                        }
                        else if (listStyleType === UPPER_ALPHA) {
                            startAttr = (startString.split('.')[0].charCodeAt(0) - 64);
                        }
                        else if (listStyleType === LOWER_ALPHA) {
                            startAttr = (startString.split('.')[0].charCodeAt(0) - 96);
                        }
                        else if (listStyleType === UPPER_ROMAN) {
                            startAttr = ClipboardCleanupModule.upperRomanNumber.indexOf(this.listContents[0].split('.')[0]) + 1;
                        }
                        else if (listStyleType === LOWER_ROMAN) {
                            startAttr = ClipboardCleanupModule.lowerRomanNumber.indexOf(this.listContents[0].split('.')[0]) + 1;
                        }
                        else if (listStyleType === LOWER_GREEK) {
                            startAttr = ClipboardCleanupModule.lowerGreekNumber.indexOf(this.listContents[0].split('.')[0]) + 1;
                        }
                    }
                }
                if (listNodes[i].style.marginLeft !== '') {
                    styleMarginLeft = listNodes[i].style.marginLeft;
                }
                var tempNode = [];
                for (var j = 1; j < this.listContents.length; j++) {
                    tempNode.push(this.listContents[j]);
                }
                var currentClassName = void 0;
                if (!isNOU(listNodes[i].className)) {
                    currentClassName = listNodes[i].className;
                }
                if (!isNOU(listNodes[i].getAttribute('style'))) {
                    listNodes[i].setAttribute('style', listNodes[i].getAttribute('style').replace('text-align:start;', ''));
                    updateCSSText(listNodes[i], 'text-indent: "";');
                    currentListStyle = listNodes[i].getAttribute('style');
                }
                collection.push({
                    listType: type, content: tempNode, nestedLevel: level,
                    listFormatOverride: listFormatOverride, class: currentClassName,
                    listStyle: currentListStyle, listStyleTypeName: listStyleType, start: startAttr, styleMarginLeft: styleMarginLeft
                });
            }
        }
        stNode = listNodes.shift();
        while (stNode) {
            var elemColl = [];
            for (var temp1 = 0; temp1 < data.length; temp1++) {
                if (data[temp1].node === stNode) {
                    for (var index = 0; index < data[temp1].content.childNodes.length; index++) {
                        elemColl.push(data[temp1].content.childNodes[index]);
                    }
                    for (var index = 0; index < elemColl.length; index++) {
                        stNode.parentElement.insertBefore(elemColl[index], stNode);
                    }
                    break;
                }
            }
            stNode.remove();
            stNode = listNodes.shift();
            if (!stNode) {
                stNode = listNodes.shift();
            }
        }
    };
    ClipboardCleanupModule.prototype.getlistStyleType = function (listContent, type) {
        var currentListClass;
        if (type === 'ol') {
            var charCode = listContent.split('.')[0].charCodeAt(0);
            switch (true) {
                case ClipboardCleanupModule.upperRomanNumber.indexOf(listContent.split('.')[0]) > -1:
                    currentListClass = UPPER_ROMAN;
                    break;
                case ClipboardCleanupModule.lowerRomanNumber.indexOf(listContent.split('.')[0]) > -1:
                    currentListClass = LOWER_ROMAN;
                    break;
                case ClipboardCleanupModule.lowerGreekNumber.indexOf(listContent.split('.')[0]) > -1:
                    currentListClass = LOWER_GREEK;
                    break;
                case (charCode > 64 && charCode < 91):
                    currentListClass = UPPER_ALPHA;
                    break;
                case (charCode > 96 && charCode < 123):
                    currentListClass = LOWER_ALPHA;
                    break;
                case (listContent.split('.')[0].length > 1 && listContent.split('.')[0][0] === '0' && !isNaN(Number(listContent.split('.')[0]))):
                    currentListClass = DECIMAL_LD_ZERO;
                    break;
                default:
                    currentListClass = DECIMAL;
                    break;
            }
        }
        else {
            switch (listContent.split('.')[0]) {
                case 'o':
                    currentListClass = CIRCLE;
                    break;
                case '§':
                    currentListClass = SQUARE;
                    break;
                default:
                    currentListClass = DISC;
                    break;
            }
        }
        return currentListClass;
    };
    /* Converts a collection of MSWord list items into HTML list elements */
    ClipboardCleanupModule.prototype.makeConversion = function (collection) {
        var rootElement = createElement('div');
        var CURRENT_ITEM_CLASS = 'e-current-list-item';
        var currentListElement;
        var currentNestingLevel = 1;
        var currentListItem;
        var listItemCount = 0;
        var currentFormatOverride = collection[0].listFormatOverride;
        for (var i = 0; i < collection.length; i++) {
            var currentItem = collection[i];
            var isStandardList = this.isStandardListType(currentItem.class);
            if (currentListItem) {
                currentListItem.classList.remove(CURRENT_ITEM_CLASS);
            }
            if (this.shouldResetListItem(currentListItem, i, collection, isStandardList)) {
                currentListItem = null;
            }
            var paragraphElement = this.createParagraphWithContent(currentItem);
            if (this.isNewRootList(currentItem, listItemCount, currentFormatOverride)) {
                currentListElement = this.createRootList(rootElement, currentItem, paragraphElement);
                currentListItem = currentListElement.querySelector('.' + CURRENT_ITEM_CLASS);
            }
            else if (this.isSameLevelList(currentItem, currentNestingLevel, currentFormatOverride)) {
                currentListElement = this.addToSameLevelList(currentItem, currentListElement, paragraphElement, currentListItem, rootElement);
                currentListItem = currentListElement.querySelector('.' + CURRENT_ITEM_CLASS);
            }
            else if (this.isDeeperNestedList(currentItem, currentNestingLevel)) {
                currentListElement = this.createNestedList(currentItem, currentListItem, paragraphElement, isStandardList, rootElement, currentNestingLevel);
                currentListItem = currentListElement.querySelector('.' + CURRENT_ITEM_CLASS);
            }
            else if (this.isTopLevelList(currentItem)) {
                currentListElement = this.handleTopLevelList(currentItem, rootElement, paragraphElement);
                currentListItem = currentListElement.querySelector('.' + CURRENT_ITEM_CLASS);
            }
            else {
                this.handleOtherNestingScenarios(currentItem, currentListItem, paragraphElement, currentFormatOverride);
                currentListItem = rootElement.querySelector('.' + CURRENT_ITEM_CLASS);
            }
            this.applyListItemStyles(currentListItem, currentItem);
            currentNestingLevel = currentItem.nestedLevel;
            currentFormatOverride = currentItem.listFormatOverride;
            listItemCount++;
            this.setStartAttributeIfNeeded(currentListElement, currentItem);
        }
        var trackedItems = rootElement.querySelectorAll('.' + CURRENT_ITEM_CLASS);
        for (var i = 0; i < trackedItems.length; i++) {
            trackedItems[i].classList.remove(CURRENT_ITEM_CLASS);
            if (trackedItems[i].className === '') {
                trackedItems[i].removeAttribute('class');
            }
        }
        return rootElement;
    };
    /* Checks if the list item is a standard list type */
    ClipboardCleanupModule.prototype.isStandardListType = function (className) {
        var standardListClasses = [
            'MsoListParagraphCxSpFirst',
            'MsoListParagraphCxSpMiddle',
            'MsoListParagraphCxSpLast'
        ];
        for (var i = 0; i < standardListClasses.length; i++) {
            if (!isNOU(className) && standardListClasses[i].indexOf(className) >= 0) {
                return true;
            }
        }
        return false;
    };
    /* Determines if the list item should be reset */
    ClipboardCleanupModule.prototype.shouldResetListItem = function (listItem, index, collection, isStandardList) {
        return !isNOU(listItem) &&
            index !== 0 &&
            collection[index - 1].listType !== collection[index].listType &&
            !isStandardList;
    };
    /* Creates a paragraph element with content */
    ClipboardCleanupModule.prototype.createParagraphWithContent = function (item) {
        var paragraphElement = createElement('p', { className: 'MsoNoSpacing' });
        paragraphElement.innerHTML = item.content.join(' ');
        return paragraphElement;
    };
    /* Checks if this is a new root list */
    ClipboardCleanupModule.prototype.isNewRootList = function (item, listCount, formatOverride) {
        return item.nestedLevel === 1 &&
            (listCount === 0 || formatOverride !== item.listFormatOverride) &&
            item.content.length > 0;
    };
    /* Creates a root list element */
    ClipboardCleanupModule.prototype.createRootList = function (rootElement, item, paragraphElement) {
        var listElement = createElement(item.listType, { className: item.class });
        var listItem = createElement('li');
        listItem.appendChild(paragraphElement);
        listElement.appendChild(listItem);
        rootElement.appendChild(listElement);
        listElement.setAttribute('level', item.nestedLevel.toString());
        if (item.class !== 'msolistparagraph') {
            updateCSSText(listElement, "margin-left: " + item.styleMarginLeft + ";");
        }
        else {
            addClass([listElement], 'marginLeftIgnore');
        }
        updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
        listItem.classList.add('e-current-list-item');
        return listElement;
    };
    /* Checks if this is a same level list item */
    ClipboardCleanupModule.prototype.isSameLevelList = function (item, currentLevel, formatOverride) {
        return item.nestedLevel === currentLevel && formatOverride === item.listFormatOverride;
    };
    /* Adds an item to a same level list */
    ClipboardCleanupModule.prototype.addToSameLevelList = function (item, listElement, paragraphElement, listItem, rootElement) {
        if (!isNOU(listItem) && !isNOU(listItem.parentElement) &&
            listItem.parentElement.tagName.toLowerCase() === item.listType) {
            var newListItem = this.createAndAppendElement(paragraphElement);
            listItem.parentElement.appendChild(newListItem);
            return listItem.parentElement;
        }
        else if (isNOU(listItem)) {
            var newListElement = createElement(item.listType);
            updateCSSText(newListElement, "list-style-type: " + item.listStyleTypeName + ";");
            var newListItem = this.createAndAppendElement(paragraphElement);
            newListElement.appendChild(newListItem);
            newListElement.setAttribute('level', item.nestedLevel.toString());
            rootElement.appendChild(newListElement);
            return newListElement;
        }
        else {
            var newListElement = createElement(item.listType);
            updateCSSText(newListElement, "list-style-type: " + item.listStyleTypeName + ";");
            var newListItem = this.createAndAppendElement(paragraphElement);
            newListElement.appendChild(newListItem);
            newListElement.setAttribute('level', item.nestedLevel.toString());
            listItem.parentElement.parentElement.appendChild(newListElement);
            return newListElement;
        }
    };
    ClipboardCleanupModule.prototype.createAndAppendElement = function (children) {
        var newListItem = createElement('li');
        newListItem.classList.add('e-current-list-item');
        newListItem.appendChild(children);
        return newListItem;
    };
    /* Checks if this is a deeper nested list */
    ClipboardCleanupModule.prototype.isDeeperNestedList = function (item, currentLevel) {
        return item.nestedLevel > currentLevel;
    };
    /* Creates a nested list */
    ClipboardCleanupModule.prototype.createNestedList = function (item, listItem, paragraphElement, isStandardList, rootElement, currentNestingLevel) {
        var listElement;
        if (!isNOU(listItem)) {
            var levelDifference = item.nestedLevel - currentNestingLevel;
            for (var j = 0; j < levelDifference; j++) {
                listElement = createElement(item.listType);
                listItem.appendChild(listElement);
                listItem = createElement('li');
                if (j !== levelDifference - 1 && levelDifference > 1) {
                    updateCSSText(listItem, 'list-style-type: none;');
                }
                listElement.appendChild(listItem);
            }
            listItem.classList.add('e-current-list-item');
            listItem.appendChild(paragraphElement);
            listElement.setAttribute('level', item.nestedLevel.toString());
            updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
            return listElement;
        }
        else if (isStandardList) {
            return this.createStandardNestedList(item, paragraphElement, rootElement);
        }
        else {
            return this.createRootList(rootElement, item, paragraphElement);
        }
    };
    /* Creates a standard nested list */
    ClipboardCleanupModule.prototype.createStandardNestedList = function (item, paragraphElement, rootElement) {
        var initialNode = createElement(item.listType);
        var listItem = createElement('li');
        var listElement;
        initialNode.appendChild(listItem);
        updateCSSText(initialNode, 'list-style-type: none;');
        for (var j = 0; j < item.nestedLevel - 1; j++) {
            listElement = createElement(item.listType);
            listItem.appendChild(listElement);
            listItem = createElement('li');
            listElement.appendChild(listItem);
            updateCSSText(listElement, 'list-style-type: none;');
        }
        listItem.classList.add('e-current-list-item');
        listItem.appendChild(paragraphElement);
        rootElement.appendChild(initialNode);
        listElement.setAttribute('level', item.nestedLevel.toString());
        updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
        return listElement;
    };
    /* Checks if this is a top-level list */
    ClipboardCleanupModule.prototype.isTopLevelList = function (item) {
        return item.nestedLevel === 1;
    };
    /* Handles top-level list creation or reuse */
    ClipboardCleanupModule.prototype.handleTopLevelList = function (item, rootElement, paragraphElement) {
        var listElement;
        var lastChild = rootElement.lastChild;
        if (lastChild && lastChild.tagName.toLowerCase() === item.listType) {
            listElement = lastChild;
        }
        else {
            listElement = createElement(item.listType);
            updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
            rootElement.appendChild(listElement);
        }
        var listItem = createElement('li');
        listItem.appendChild(paragraphElement);
        listElement.appendChild(listItem);
        listElement.setAttribute('level', item.nestedLevel.toString());
        listItem.classList.add('e-current-list-item');
        return listElement;
    };
    /* Handles other nesting scenarios */
    ClipboardCleanupModule.prototype.handleOtherNestingScenarios = function (item, listItem, paragraphElement, currentFormatOverride) {
        var currentElement = listItem;
        var listElement;
        while (currentElement.parentElement) {
            currentElement = currentElement.parentElement;
            var levelAttribute = currentElement.attributes.getNamedItem('level');
            if (levelAttribute) {
                var elementLevel = parseInt(levelAttribute.textContent, 10);
                if (elementLevel === item.nestedLevel && currentFormatOverride === item.listFormatOverride) {
                    var newListItem = createElement('li');
                    newListItem.appendChild(paragraphElement);
                    currentElement.appendChild(newListItem);
                    newListItem.classList.add('e-current-list-item');
                    break;
                }
                else if (elementLevel === item.nestedLevel && currentFormatOverride !== item.listFormatOverride) {
                    this.createDifferentFormatList(item, currentElement, paragraphElement);
                    break;
                }
                else if (item.nestedLevel > elementLevel) {
                    listElement = createElement(item.listType);
                    var newListItem = createElement('li');
                    newListItem.appendChild(paragraphElement);
                    listElement.appendChild(newListItem);
                    currentElement.appendChild(listElement);
                    listElement.setAttribute('level', item.nestedLevel.toString());
                    updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
                    newListItem.classList.add('e-current-list-item');
                    break;
                }
            }
        }
    };
    /* Creates a list with different format override */
    ClipboardCleanupModule.prototype.createDifferentFormatList = function (item, parentElement, paragraphElement) {
        var listElement = createElement(item.listType);
        var listItem = createElement('li');
        listElement.appendChild(listItem);
        if (item.nestedLevel > 1) {
            for (var k = 0; k < item.nestedLevel - 1; k++) {
                listItem.appendChild(listElement = createElement(item.listType));
                listItem = createElement('li');
                listElement.appendChild(listItem);
                updateCSSText(listElement, 'list-style-type: none;');
            }
        }
        listItem.appendChild(paragraphElement);
        listItem.classList.add('e-current-list-item');
        parentElement.appendChild(listElement);
        listElement.setAttribute('level', item.nestedLevel.toString());
        updateCSSText(listElement, "list-style-type: " + item.listStyleTypeName + ";");
    };
    /* Applies styles and attributes to a list item */
    ClipboardCleanupModule.prototype.applyListItemStyles = function (listItem, item) {
        if (isNOU(listItem)) {
            return;
        }
        listItem.setAttribute('class', item.class);
        listItem.style.cssText = !isNOU(item.listStyle) ? item.listStyle : '';
    };
    /* Sets start attribute if needed */
    ClipboardCleanupModule.prototype.setStartAttributeIfNeeded = function (listElement, item) {
        var needsStartAttribute = !isNOU(item.start) &&
            item.start !== 1 && item.listType === 'ol';
        if (needsStartAttribute) {
            listElement.setAttribute('start', item.start.toString());
        }
    };
    /* Extracts list content from an element */
    ClipboardCleanupModule.prototype.getListContent = function (element) {
        var firstChild = element.firstElementChild;
        if (this.isImageList(firstChild)) {
            this.handleImageList(element);
        }
        else if (firstChild.childNodes.length > 0) {
            this.handleTextList(element, firstChild);
        }
        this.listContents.push(element.innerHTML);
    };
    /* Checks if this is an image list */
    ClipboardCleanupModule.prototype.isImageList = function (firstChild) {
        return firstChild.textContent.trim() === '' &&
            !isNOU(firstChild.firstElementChild) &&
            firstChild.firstElementChild.nodeName === 'IMG';
    };
    /* Handles image list content */
    ClipboardCleanupModule.prototype.handleImageList = function (element) {
        var content = element.innerHTML.trim();
        this.listContents.push('');
        this.listContents.push(content);
    };
    /* Handles text list content */
    ClipboardCleanupModule.prototype.handleTextList = function (element, firstChild) {
        this.cleanupListIgnoreTags(firstChild);
        var listOrderElement = this.cleanupListOrder(firstChild);
        this.processListOrderElement(element, firstChild, listOrderElement);
    };
    /* Cleans up list ignore tags */
    ClipboardCleanupModule.prototype.cleanupListIgnoreTags = function (firstChild) {
        var listIgnoreTags = firstChild.querySelectorAll('[style*="mso-list"]');
        for (var i = 0; i < listIgnoreTags.length; i++) {
            var tag = listIgnoreTags[i];
            var style = tag.getAttribute('style').replace(/\n/g, '');
            tag.setAttribute('style', style);
        }
    };
    /* Cleans up list order element */
    ClipboardCleanupModule.prototype.cleanupListOrder = function (firstChild) {
        var listOrderCleanup = firstChild.querySelector('span[style*="mso-list"]');
        if (listOrderCleanup) {
            var style = listOrderCleanup.getAttribute('style');
            if (style) {
                style = style.replace(/\s*:\s*/g, ':');
                listOrderCleanup.setAttribute('style', style);
            }
        }
        return firstChild.querySelector('span[style="mso-list:Ignore"]');
    };
    /* Processes list order element */
    ClipboardCleanupModule.prototype.processListOrderElement = function (element, firstChild, listOrderElement) {
        var isEmptyMarkerSpan = isNOU(listOrderElement);
        listOrderElement = isEmptyMarkerSpan ? firstChild : listOrderElement;
        if (!isNOU(listOrderElement)) {
            var textContent = listOrderElement.textContent.trim();
            if (isEmptyMarkerSpan) {
                textContent = this.extractBulletMarker(listOrderElement, textContent);
            }
            this.listContents.push(textContent);
            if (!isEmptyMarkerSpan) {
                detach(listOrderElement);
            }
            this.removeComments(element);
            this.removeUnwantedElements(element);
        }
    };
    /* Extracts bullet marker from text content */
    ClipboardCleanupModule.prototype.extractBulletMarker = function (listOrderElement, textContent) {
        var bulletPattern = /^(\d{1,2}|[a-zA-Z]|[*#~•○■])(\.|\)|-)\s*/;
        var textContentMatch = textContent.match(bulletPattern);
        if (!isNOU(textContentMatch)) {
            var markerText = textContentMatch[0].trim();
            listOrderElement.textContent = listOrderElement.textContent.trim().substring(markerText.length).trim();
            return markerText;
        }
        return textContent;
    };
    ClipboardCleanupModule.prototype.cleanupHtml = function (html, keepFormat) {
        var tempDiv = createElement('div');
        tempDiv.innerHTML = html;
        this.removeUnwantedElements(tempDiv);
        // Normalize and sanitize any tables in generic HTML (non-Word)
        this.processTables(tempDiv);
        if (!keepFormat) {
            this.deniedAttributes(tempDiv, true);
        }
        else if (this.parent.pasteCleanupSettings.deniedTags && this.parent.pasteCleanupSettings.deniedTags.length > 0) {
            this.deniedAttributes(tempDiv, false);
        }
        if (this.parent.pasteCleanupSettings.allowedStyles && this.parent.pasteCleanupSettings.allowedStyles.length > 0) {
            this.allowedStyle(tempDiv);
        }
        if (this.parent.pasteCleanupSettings.deniedTags && this.parent.pasteCleanupSettings.deniedTags.length > 0) {
            this.deniedTags(tempDiv);
        }
        this.removeEmptyElements(tempDiv);
        this.removeComments(tempDiv);
        this.processImages(tempDiv);
        this.cleanupCssPatterns(tempDiv);
        return tempDiv.innerHTML;
    };
    ClipboardCleanupModule.prototype.plainFormatting = function (html) {
        var tempDiv = createElement('div');
        tempDiv.innerHTML = html;
        this.detachInlineElements(tempDiv);
        this.getTextContent(tempDiv);
        this.removeEmptyElements(tempDiv);
        this.removeComments(tempDiv);
        return tempDiv.innerHTML;
    };
    ClipboardCleanupModule.prototype.removeUnwantedElements = function (element) {
        this.removeStyleElements(element);
        var innerElement = element.innerHTML;
        for (var i = 0; i < ClipboardCleanupModule.removableElements.length; i++) {
            // eslint-disable-next-line security/detect-non-literal-regexp
            var regExpStartElem = new RegExp('<' + ClipboardCleanupModule.removableElements[i] + '\\s*[^>]*>', 'g');
            // eslint-disable-next-line security/detect-non-literal-regexp
            var regExpEndElem = new RegExp('</' + ClipboardCleanupModule.removableElements[i] + '>', 'g');
            innerElement = innerElement.replace(regExpStartElem, '');
            innerElement = innerElement.replace(regExpEndElem, '');
        }
        element.innerHTML = innerElement;
    };
    ClipboardCleanupModule.prototype.removeStyleElements = function (element) {
        var styleElement = element.querySelector('style');
        if (!isNOU(styleElement)) {
            detach(styleElement);
        }
    };
    ClipboardCleanupModule.prototype.removeComments = function (element) {
        var innerElement = element.innerHTML;
        innerElement = innerElement.replace(/<!--[\s\S]*?-->/g, '');
        element.innerHTML = innerElement;
    };
    ClipboardCleanupModule.prototype.removeEmptyElements = function (element) {
        var emptyElements = element.querySelectorAll(':empty');
        for (var i = 0; i < emptyElements.length; i++) {
            if (emptyElements[i].tagName !== 'IMG' &&
                emptyElements[i].tagName !== 'BR' &&
                emptyElements[i].tagName !== 'IFRAME' &&
                emptyElements[i].tagName !== 'TD' &&
                emptyElements[i].tagName !== 'HR') {
                var detachableElement = this.findDetachEmptyElem(emptyElements[i]);
                if (!isNOU(detachableElement)) {
                    detach(detachableElement);
                }
            }
        }
    };
    ClipboardCleanupModule.prototype.findDetachEmptyElem = function (element) {
        var removableElement;
        if (!isNOU(element.parentElement)) {
            var hasNbsp = element.parentElement.textContent.length > 0 &&
                element.parentElement.textContent.match(/\u00a0/g) &&
                element.parentElement.textContent.match(/\u00a0/g).length > 0;
            if (!hasNbsp && element.parentElement.textContent.trim() === '' &&
                isNOU(element.parentElement.querySelector('img'))) {
                removableElement = this.findDetachEmptyElem(element.parentElement);
            }
            else {
                removableElement = element;
            }
        }
        else {
            removableElement = null;
        }
        return removableElement;
    };
    ClipboardCleanupModule.prototype.removeWordClasses = function (element) {
        var elementsWithClass = element.querySelectorAll('*[class]');
        var _loop_1 = function (i) {
            var classList = elementsWithClass[i].classList;
            var classesToRemove = [];
            for (var j = 0; j < classList.length; j++) {
                if (classList[j].indexOf('Mso') === 0) {
                    classesToRemove.push(classList[j]);
                }
            }
            classesToRemove.forEach(function (className) {
                elementsWithClass[i].classList.remove(className);
            });
            if (elementsWithClass[i].classList.length === 0) {
                elementsWithClass[i].removeAttribute('class');
            }
        };
        for (var i = 0; i < elementsWithClass.length; i++) {
            _loop_1(i);
        }
    };
    ClipboardCleanupModule.prototype.cleanupStyles = function (element, allowedStyles) {
        var elementsWithStyle = element.querySelectorAll('*[style]');
        for (var i = 0; i < elementsWithStyle.length; i++) {
            var styleAttr = elementsWithStyle[i].getAttribute('style');
            if (!styleAttr) {
                continue;
            }
            var styles = styleAttr.split(';');
            var newStyles = '';
            for (var j = 0; j < styles.length; j++) {
                var style = styles[j].trim();
                if (!style) {
                    continue;
                }
                var _a = style.split(':').map(function (s) { return s.trim(); }), property = _a[0], value = _a[1];
                if (property.indexOf('mso-') === 0) {
                    continue;
                }
                if (allowedStyles.indexOf(property) !== -1) {
                    newStyles += property + ": " + value + "; ";
                }
            }
            if (newStyles) {
                elementsWithStyle[i].setAttribute('style', newStyles.trim());
            }
            else {
                elementsWithStyle[i].removeAttribute('style');
            }
        }
    };
    ClipboardCleanupModule.prototype.processTables = function (element) {
        var tables = element.querySelectorAll('table');
        for (var i = 0; i < tables.length; i++) {
            this.sanitizeTableElement(tables[i]);
        }
    };
    ClipboardCleanupModule.prototype.sanitizeTableElement = function (table) {
        table.classList.add('e-blockeditor-table');
        // Remove unwanted attributes
        var attrs = ['border', 'cellpadding', 'cellspacing', 'width', 'height', 'style'];
        attrs.forEach(function (attr) { if (table.hasAttribute(attr)) {
            table.removeAttribute(attr);
        } });
        // Remove colgroup/col sizing; our TableService will manage widths
        var colgroups = table.querySelectorAll('colgroup, col');
        for (var i = 0; i < colgroups.length; i++) {
            colgroups[i].parentElement.removeChild(colgroups[i]);
        }
        var cells = table.querySelectorAll('td, th');
        var _loop_2 = function (j) {
            var cell = cells[j];
            // Remove spans unsupported by editor
            cell.removeAttribute('rowspan');
            cell.removeAttribute('colspan');
            // Remove unwanted attributes/styles
            ['width', 'height', 'style'].forEach(function (attr) { if (cell.hasAttribute(attr)) {
                cell.removeAttribute(attr);
            } });
            // Ensure minimal content wrapper
            if (cell.textContent.trim() === '' && !cell.querySelector('img') && !cell.querySelector('.e-table-cell-host')) {
                cell.innerHTML = '<p><br/></p>';
            }
        };
        for (var j = 0; j < cells.length; j++) {
            _loop_2(j);
        }
    };
    ClipboardCleanupModule.prototype.cleanupLists = function (element) {
        this.cleanList(element, 'UL');
        this.cleanList(element, 'OL');
        this.convertWordListParagraphs(element);
    };
    ClipboardCleanupModule.prototype.cleanList = function (element, listTag) {
        var replacableElem = element.querySelectorAll(listTag + " div");
        for (var j = replacableElem.length - 1; j >= 0; j--) {
            var parentElem = replacableElem[j].parentNode;
            while (replacableElem[j].firstChild) {
                parentElem.insertBefore(replacableElem[j].firstChild, replacableElem[j]);
            }
            var closestListElem = this.findClosestListElem(replacableElem[j]);
            if (closestListElem) {
                this.insertAfter(replacableElem[j], closestListElem);
            }
        }
    };
    ClipboardCleanupModule.prototype.findClosestListElem = function (listElem) {
        var closestListElem;
        while (!isNOU(listElem)) {
            listElem = !isNOU(listElem.closest('ul')) && listElem.tagName !== 'UL'
                ? listElem.closest('ul')
                : (listElem.tagName !== 'OL' ? listElem.closest('ol') : null);
            closestListElem = !isNOU(listElem) ? listElem : closestListElem;
        }
        return closestListElem;
    };
    ClipboardCleanupModule.prototype.insertAfter = function (newNode, referenceNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    };
    ClipboardCleanupModule.prototype.convertWordListParagraphs = function (element) {
        var listParagraphs = element.querySelectorAll('p[style*="mso-list"]');
        if (listParagraphs.length === 0) {
            return;
        }
        var currentList = null;
        var currentListType = null;
        var currentLevel = 0;
        for (var i = 0; i < listParagraphs.length; i++) {
            var paragraph = listParagraphs[i];
            var listType = 'ul';
            var textContent = paragraph.textContent.trim();
            if (/^\d+\./.test(textContent) || /^[a-zA-Z]\./.test(textContent) || /^[ivxIVX]+\./.test(textContent)) {
                listType = 'ol';
            }
            var level = 1;
            var styleAttr = paragraph.getAttribute('style');
            if (styleAttr) {
                var levelMatch = styleAttr.match(/level(\d+)/);
                if (levelMatch) {
                    level = parseInt(levelMatch[1], 10);
                }
            }
            var content = paragraph.innerHTML;
            content = content.replace(/^[\s\u00A0]*(?:\d+\.|\w\.|\u2022|\u25CF|\u25CB|\u25A0|\u25A1)[\s\u00A0]+/, '');
            if (!currentList || currentListType !== listType || level < currentLevel) {
                currentList = document.createElement(listType);
                currentListType = listType;
                paragraph.parentNode.insertBefore(currentList, paragraph);
            }
            var listItem = document.createElement('li');
            listItem.innerHTML = content;
            currentList.appendChild(listItem);
            currentLevel = level;
            paragraph.parentNode.removeChild(paragraph);
        }
    };
    ClipboardCleanupModule.prototype.processImages = function (element) {
        var images = element.querySelectorAll('img');
        for (var i = 0; i < images.length; i++) {
            var img = images[i];
            img.classList.add('e-blockeditor-pasted-img');
            if (!img.hasAttribute('alt')) {
                img.setAttribute('alt', 'Pasted image');
            }
        }
    };
    ClipboardCleanupModule.prototype.cleanupCssPatterns = function (root) {
        var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
            acceptNode: function (node) {
                var text = node.textContent.trim();
                var isInlineStyle = text.match(/^\s*(ol|ul|li)[\s\S]*?\{[\s\S]*?\}/i);
                return isInlineStyle ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            }
        });
        var nodesToRemove = [];
        while (walker.nextNode()) {
            var node = walker.currentNode;
            nodesToRemove.push(node);
        }
        for (var _i = 0, nodesToRemove_1 = nodesToRemove; _i < nodesToRemove_1.length; _i++) {
            var node = nodesToRemove_1[_i];
            node.remove();
        }
    };
    ClipboardCleanupModule.prototype.deniedTags = function (element) {
        var deniedTags = this.parent.pasteCleanupSettings.deniedTags;
        for (var i = 0; i < deniedTags.length; i++) {
            var removableElements = element.querySelectorAll(deniedTags[i]);
            for (var j = removableElements.length - 1; j >= 0; j--) {
                var parentElem = removableElements[j].parentNode;
                while (removableElements[j].firstChild) {
                    parentElem.insertBefore(removableElements[j].firstChild, removableElements[j]);
                }
                parentElem.removeChild(removableElements[j]);
            }
        }
        return element;
    };
    ClipboardCleanupModule.prototype.deniedAttributes = function (element, clean) {
        var deniedAttrs = clean ? ['style', 'class'] : this.parent.pasteCleanupSettings.deniedTags;
        for (var i = 0; i < deniedAttrs.length; i++) {
            var elementsWithAttr = element
                .querySelectorAll("[" + deniedAttrs[i] + "]");
            for (var j = 0; j < elementsWithAttr.length; j++) {
                elementsWithAttr[j].removeAttribute(deniedAttrs[i]);
            }
        }
        return element;
    };
    ClipboardCleanupModule.prototype.allowedStyle = function (element) {
        var allowedStyles = this.parent.pasteCleanupSettings.allowedStyles;
        var styleElements = element.querySelectorAll('[style]');
        for (var i = 0; i < styleElements.length; i++) {
            var allowedStyleValue = '';
            var styleValue = styleElements[i].getAttribute('style').split(';');
            for (var j = 0; j < styleValue.length; j++) {
                var stylePair = styleValue[j].trim();
                if (!stylePair) {
                    continue;
                }
                var property = stylePair.split(':').map(function (s) { return s.trim(); })[0];
                if (allowedStyles.indexOf(property) !== -1) {
                    allowedStyleValue += stylePair + ';';
                }
            }
            styleElements[i].removeAttribute('style');
            if (allowedStyleValue) {
                styleElements[i].setAttribute('style', allowedStyleValue);
            }
        }
        return element;
    };
    ClipboardCleanupModule.prototype.detachInlineElements = function (element) {
        for (var i = 0; i < ClipboardCleanupModule.inlineNode.length; i++) {
            var inlineElements = element.querySelectorAll(ClipboardCleanupModule.inlineNode[i]);
            for (var j = 0; j < inlineElements.length; j++) {
                var parentElem = inlineElements[j].parentElement;
                if (!parentElem) {
                    continue;
                }
                while (inlineElements[j].firstChild) {
                    parentElem.insertBefore(inlineElements[j].firstChild, inlineElements[j]);
                }
                parentElem.removeChild(inlineElements[j]);
            }
        }
    };
    ClipboardCleanupModule.prototype.getTextContent = function (element) {
        for (var i = 0; i < ClipboardCleanupModule.blockNode.length; i++) {
            var blockElements = element.querySelectorAll(ClipboardCleanupModule.blockNode[i]);
            for (var j = 0; j < blockElements.length; j++) {
                var paragraph = document.createElement('p');
                paragraph.textContent = blockElements[j].textContent;
                blockElements[j].parentNode.replaceChild(paragraph, blockElements[j]);
            }
        }
        var allElements = element.querySelectorAll('*');
        for (var i = 0; i < allElements.length; i++) {
            var attributes = allElements[i].attributes;
            for (var j = attributes.length - 1; j >= 0; j--) {
                allElements[i].removeAttribute(attributes[j].name);
            }
        }
    };
    ClipboardCleanupModule.inlineNode = ['a', 'abbr', 'acronym', 'audio', 'b', 'bdi', 'bdo', 'big', 'br', 'button',
        'canvas', 'cite', 'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'font', 'i', 'iframe', 'img', 'input',
        'ins', 'kbd', 'label', 'map', 'mark', 'meter', 'noscript', 'object', 'output', 'picture', 'progress',
        'q', 'ruby', 's', 'samp', 'script', 'select', 'slot', 'small', 'span', 'strong', 'sub', 'sup', 'svg',
        'template', 'textarea', 'time', 'u', 'tt', 'var', 'video', 'wbr'];
    ClipboardCleanupModule.blockNode = ['div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'address', 'blockquote', 'button', 'center', 'dd', 'dir', 'dl', 'dt', 'fieldset',
        'frameset', 'hr', 'iframe', 'isindex', 'li', 'map', 'menu', 'noframes', 'noscript',
        'object', 'ol', 'pre', 'td', 'tr', 'th', 'tbody', 'tfoot', 'thead', 'table', 'ul',
        'header', 'article', 'nav', 'footer', 'section', 'aside', 'main', 'figure', 'figcaption'];
    ClipboardCleanupModule.removableElements = ['o:p', 'style', 'w:sdt', 'xml', 'script', 'meta', 'link'];
    ClipboardCleanupModule.ignorableNodes = ['A', 'APPLET', 'B', 'BLOCKQUOTE', 'BR',
        'BUTTON', 'CENTER', 'CODE', 'COL', 'COLGROUP', 'DD', 'DEL', 'DFN', 'DIR', 'DIV',
        'DL', 'DT', 'EM', 'FIELDSET', 'FONT', 'FORM', 'FRAME', 'FRAMESET', 'H1', 'H2',
        'H3', 'H4', 'H5', 'H6', 'HR', 'I', 'IMG', 'IFRAME', 'INPUT', 'INS', 'LABEL',
        'LI', 'OL', 'OPTION', 'P', 'PARAM', 'PRE', 'Q', 'S', 'SELECT', 'SPAN', 'STRIKE',
        'STRONG', 'SUB', 'SUP', 'TABLE', 'TBODY', 'TD', 'TEXTAREA', 'TFOOT', 'TH',
        'THEAD', 'TITLE', 'TR', 'TT', 'U', 'UL'];
    ClipboardCleanupModule.upperRomanNumber = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX',
        'X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX'];
    ClipboardCleanupModule.lowerRomanNumber = ['i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix',
        'x', 'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'xvii', 'xviii', 'xix', 'xx'];
    ClipboardCleanupModule.lowerGreekNumber = ['α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ',
        'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω'];
    ClipboardCleanupModule.msWordPatterns = [
        /class='?Mso|style='[^ ]*\bmso-/i,
        /class="?Mso|style="[^ ]*\bmso-/i,
        /(class="?Mso|class='?Mso|class="?Xl|class='?Xl|class=Xl|style="[^"]*\bmso-|style='[^']*\bmso-|w:WordDocument)/gi,
        /style='mso-width-source:/i,
        // New Office 365 patterns
        /\bOutlineElement\b/i,
        /\bSCXW\d+\b/i,
        /\bBCX\d+\b/i,
        /\bTextRun\b/i,
        /\bEOP\b/i,
        /\bpara(id|eid)=/i,
        /data-ccp-/i,
        /\bWACImageContainer\b/i // Word's image container
    ];
    return ClipboardCleanupModule;
}());
export { ClipboardCleanupModule };
