All files / roosterjs-content-model-core/lib/command/paste cleanHtmlComments.ts

100% Statements 32/32
100% Branches 6/6
100% Functions 3/3
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 551x 1x 1x 1x 1x 1x           1x 11x   11x 10x 10x 10x   10x     11x     32x 21x 21x 21x 21x   21x 3x 3x 3x     21x 21x                 30x 30x 22x 22x   30x    
const HtmlCommentStart = '\x3C!--';
const HtmlCommentStart2 = '<!--';
const HtmlCommentEnd = '-->';
const styleTag = '<style';
const styleClosingTag = '</style>';
const nonWordCharacterRegex = /\W/;
 
/**
 * @internal
 * Exported only for unit test
 */
export function cleanHtmlComments(html: string) {
    let { styleIndex, styleEndIndex } = extractHtmlIndexes(html);
 
    while (styleIndex > -1) {
        html = removeCommentsFromHtml(html, HtmlCommentStart, styleEndIndex, styleIndex);
        html = removeCommentsFromHtml(html, HtmlCommentStart2, styleEndIndex, styleIndex);
        html = removeCommentsFromHtml(html, HtmlCommentEnd, styleEndIndex, styleIndex);
 
        ({ styleIndex, styleEndIndex } = extractHtmlIndexes(html, styleEndIndex + 1));
    }
 
    return html;
}
 
function extractHtmlIndexes(html: string, startIndex: number = 0) {
    const htmlLowercase = html.toLowerCase();
    let styleIndex = htmlLowercase.indexOf(styleTag, startIndex);
    let currentIndex = styleIndex + styleTag.length;
    let nextChar = html.substring(currentIndex, currentIndex + 1);
 
    while (!nonWordCharacterRegex.test(nextChar) && styleIndex > -1) {
        styleIndex = htmlLowercase.indexOf(styleTag, styleIndex + 1);
        currentIndex = styleIndex + styleTag.length;
        nextChar = html.substring(currentIndex, currentIndex + 1);
    }
 
    const styleEndIndex = htmlLowercase.indexOf(styleClosingTag, startIndex);
    return { styleIndex, styleEndIndex };
}
 
function removeCommentsFromHtml(
    html: string,
    marker: string,
    endId: number,
    startId: number
): string {
    let id = html.indexOf(marker, startId);
    while (id > -1 && id < endId) {
        html = html.substring(0, id) + html.substring(id + marker.length);
        id = html.indexOf(marker, id + 1);
    }
    return html;
}