All files / roosterjs-content-model-dom/lib/domUtils getRangesByText.ts

97.83% Statements 45/46
91.49% Branches 43/47
100% Functions 6/6
97.73% Lines 43/44

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 1431x 1x 1x   1x                                               1x             13x                   13x 12x     13x       26x       33x   33x 49x 27x       27x 27x 27x   22x 21x 2x     21x       33x 18x           20x   20x 22x           21x 21x           21x 21x   21x 21x 21x       22x     20x 20x       9x               42x   42x 51x   51x     42x     9x          
import { isBlockElement } from '../domToModel/utils/isBlockElement';
import { isNodeOfType } from './isNodeOfType';
import { isPunctuation, isSpace } from './stringUtil';
 
const SplittingTags: string[] = ['BR', 'HR', 'IMG'];
 
interface SearchContext {
    text: string;
    matchCase: boolean;
    wholeWord: boolean;
    result: Range[];
    paragraphText: string;
    editableOnly: boolean;
    indexes: {
        node: Text;
        length: number;
    }[];
}
 
/**
 * Search text from the given root element and return all ranges that match the search criteria
 * @param root Root element to search from
 * @param text Text to search for
 * @param matchCase Whether to match case
 * @param wholeWord Whether to match whole words only
 * @param editableOnly Whether to search only in editable elements
 * @returns Array of matching ranges
 */
export function getRangesByText(
    root: HTMLElement,
    text: string,
    matchCase: boolean,
    wholeWord: boolean,
    editableOnly?: boolean
): Range[] {
    const context: SearchContext = {
        text: matchCase ? text : text.toLowerCase(),
        matchCase,
        wholeWord,
        result: [],
        paragraphText: '',
        indexes: [],
        editableOnly: !!editableOnly,
    };
 
    if (context.text) {
        iterateTextNodes(root, context);
    }
 
    return context.result;
}
 
function isSplittingElement(element: HTMLElement) {
    return isBlockElement(element) || SplittingTags.indexOf(element.tagName) >= 0;
}
 
function iterateTextNodes(root: HTMLElement, context: SearchContext) {
    const canSearchText = !context.editableOnly || root.isContentEditable;
 
    for (let node = root.firstChild; node; node = node.nextSibling) {
        if (isNodeOfType(node, 'TEXT_NODE') && canSearchText) {
            const nodeText = context.matchCase
                ? node.nodeValue || ''
                : (node.nodeValue || '').toLowerCase();
 
            Eif (nodeText) {
                context.paragraphText += nodeText;
                context.indexes.push({ node, length: nodeText.length });
            }
        } else if (isNodeOfType(node, 'ELEMENT_NODE')) {
            if (context.paragraphText && isSplittingElement(node)) {
                search(root.ownerDocument, context);
            }
 
            iterateTextNodes(node, context);
        }
    }
 
    if (context.paragraphText && isSplittingElement(root)) {
        search(root.ownerDocument, context);
    }
}
 
function search(doc: Document, context: SearchContext) {
    let offset: number;
    let startIndex = 0;
 
    while ((offset = context.paragraphText.indexOf(context.text, startIndex)) > -1) {
        if (
            !context.wholeWord ||
            ((offset == 0 || isSpaceOrPunctuation(context.paragraphText[offset - 1])) &&
                (offset + context.text.length == context.paragraphText.length ||
                    isSpaceOrPunctuation(context.paragraphText[offset + context.text.length])))
        ) {
            const start = findNodeAndOffset(context.indexes, offset, false /*isEnd*/);
            const end = findNodeAndOffset(
                context.indexes,
                offset + context.text.length,
                true /*isEnd*/
            );
 
            Eif (start && end) {
                const range = doc.createRange();
 
                range.setStart(start.node, start.offset);
                range.setEnd(end.node, end.offset);
                context.result.push(range);
            }
        }
 
        startIndex = offset + context.text.length;
    }
 
    context.paragraphText = '';
    context.indexes = [];
}
 
function isSpaceOrPunctuation(char: string) {
    return isSpace(char) || isPunctuation(char);
}
 
function findNodeAndOffset(
    lengths: { length: number; node: Text }[],
    offset: number,
    isEnd: boolean
): { node: Text; offset: number } | null {
    let currentIndex = 0;
 
    for (let i = 0; i < lengths.length; i++) {
        const segmentLength = lengths[i].length;
 
        if (
            isEnd ? currentIndex + segmentLength >= offset : currentIndex + segmentLength > offset
        ) {
            return { node: lengths[i].node, offset: offset - currentIndex };
        }
 
        currentIndex += segmentLength;
    }
 
    return null;
}