all files / common/ highlight-search.js

100% Statements 25/25
93.75% Branches 15/16
100% Functions 4/4
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40   40× 13×     27× 27× 27×   27×     37× 41× 31× 31× 31× 31×     10×              
define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function highlightSearch(element, query, ignoreCase, type) {
        if (query === '') {
            return;
        }
        else {
            var ignoreRegex = ignoreCase ? 'gim' : 'gm';
            query = /^[a-zA-Z0-9- ]*$/.test(query) ? query : query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
            var replaceQuery = type === 'StartsWith' ? '^(' + query + ')' : type === 'EndsWith' ?
                '(' + query + ')$' : '(' + query + ')';
            findTextNode(element, new RegExp(replaceQuery, ignoreRegex));
        }
    }
    exports.highlightSearch = highlightSearch;
    function findTextNode(element, pattern) {
        for (var index = 0; element.childNodes && (index < element.childNodes.length); index++) {
            if (element.childNodes[index].nodeType === 3 && element.childNodes[index].textContent.trim() !== '') {
                var value = element.childNodes[index].nodeValue.trim().replace(pattern, '<span class="e-highlight">$1</span>');
                element.childNodes[index].nodeValue = '';
                element.innerHTML = element.innerHTML.trim() + value;
                break;
            }
            else {
                findTextNode(element.childNodes[index], pattern);
            }
        }
    }
    function revertHighlightSearch(content) {
        var contentElement = content.querySelectorAll('.e-highlight');
        for (var i = contentElement.length - 1; i >= 0; i--) {
            var parent_1 = contentElement[i].parentNode;
            var text = document.createTextNode(contentElement[i].textContent);
            parent_1.replaceChild(text, contentElement[i]);
        }
    }
    exports.revertHighlightSearch = revertHighlightSearch;
});