All files / roosterjs-content-model-plugins/lib/edit/utils splitParagraph.ts

100% Statements 21/21
100% Branches 12/12
100% Functions 1/1
100% Lines 21/21

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 631x 1x                                             1x   64x 66x   90x 45x           45x 45x   45x 45x         45x   45x 45x   45x 17x 28x 27x     45x   45x   45x    
import { preserveParagraphFormat } from './preserveParagraphFormat';
import {
    copyFormat,
    createBr,
    createParagraph,
    normalizeParagraph,
    ParagraphFormats,
    setParagraphNotImplicit,
} from 'roosterjs-content-model-dom';
import type {
    InsertPoint,
    ShallowMutableContentModelParagraph,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Split the given paragraph from insert point into two paragraphs,
 * and move the selection marker to the beginning of the second paragraph
 * @param insertPoint The input insert point which includes the paragraph and selection marker
 * @param removeImplicitParagraph Whether to remove the implicit paragraph if it becomes empty after split
 * * If set to false, the implicit paragraph will be preserved even if it becomes empty
 * * If set to true, the implicit paragraph will be removed if it becomes empty
 * @returns The new paragraph it created
 */
export function splitParagraph(
    insertPoint: InsertPoint,
    removeImplicitParagraph: boolean = true,
    formatsToPreserveOnMerge: string[] = []
): ShallowMutableContentModelParagraph {
    const { paragraph, marker } = insertPoint;
    const newParagraph: ShallowMutableContentModelParagraph = createParagraph(
        false /*isImplicit*/,
        {},
        paragraph.segmentFormat
    );
 
    copyFormat(newParagraph.format, paragraph.format, ParagraphFormats);
    preserveParagraphFormat(formatsToPreserveOnMerge, paragraph, newParagraph);
 
    const markerIndex = paragraph.segments.indexOf(marker);
    const segments = paragraph.segments.splice(
        markerIndex,
        paragraph.segments.length - markerIndex
    );
 
    newParagraph.segments.push(...segments);
 
    const isEmptyParagraph = paragraph.segments.length == 0;
    const shouldPreserveImplicitParagraph = !paragraph.isImplicit || !removeImplicitParagraph;
 
    if (isEmptyParagraph && shouldPreserveImplicitParagraph) {
        paragraph.segments.push(createBr(marker.format));
    } else if (!isEmptyParagraph) {
        setParagraphNotImplicit(paragraph);
    }
 
    insertPoint.paragraph = newParagraph;
 
    normalizeParagraph(paragraph);
 
    return newParagraph;
}