All files / roosterjs-content-model-plugins/lib/findReplace replace.ts

100% Statements 23/23
93.75% Branches 15/16
100% Functions 1/1
100% Lines 23/23

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 611x 1x 1x                     1x       6x   6x 5x 5x   5x 6x   6x 2x   4x   4x 4x             4x       5x   5x 3x     5x 3x 3x           1x      
import { ChangeSource } from 'roosterjs-content-model-dom';
import { replaceTextInRange } from './utils/replaceTextInRange';
import { setMarkedIndex } from './utils/setMarkedIndex';
import type { IEditor } from 'roosterjs-content-model-types';
import type { FindReplaceContext } from './types/FindReplaceContext';
 
/**
 * Replace the currently found item or all found items in the editor
 * @param editor The editor instance
 * @param context The FindReplaceContext to use
 * @param replaceText The text to replace with
 * @param replaceAll Whether to replace all found items
 */
export function replace(
    editor: IEditor,
    context: FindReplaceContext,
    replaceText: string,
    IreplaceAll: boolean = false
): void {
    if (context.text) {
        editor.takeSnapshot();
        let isReplaced = false;
 
        do {
            const range = context.ranges[context.markedIndex];
 
            if (!range || !editor.getDOMHelper().isNodeInEditor(range.startContainer)) {
                setMarkedIndex(editor, context, 0);
            } else {
                const resultRange = replaceTextInRange(range, replaceText, context.ranges);
 
                context.ranges.splice(context.markedIndex, 1);
                setMarkedIndex(
                    editor,
                    context,
                    context.markedIndex >= context.ranges.length ? 0 : context.markedIndex,
                    resultRange
                );
 
                isReplaced = true;
            }
        } while (replaceAll && context.ranges[context.markedIndex]);
 
        context.findHighlight.clear();
 
        if (context.ranges.length > 0) {
            context.findHighlight.addRanges(context.ranges);
        }
 
        if (isReplaced) {
            editor.takeSnapshot();
            editor.triggerEvent('contentChanged', {
                data: replaceText,
                source: ChangeSource.Replace,
            });
        }
    } else {
        setMarkedIndex(editor, context, -1);
    }
}