All files / roosterjs-content-model-dom/lib/modelApi/common addTextSegment.ts

100% Statements 16/16
85.71% Branches 18/21
100% Functions 1/1
100% Lines 16/16

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 491x 1x 1x 1x 1x 1x                           1x             1852x 1724x   1724x         1340x   1340x 93x     1340x   1340x       1852x    
import { addDecorators } from './addDecorators';
import { addSegment } from './addSegment';
import { createText } from '../creators/createText';
import { ensureParagraph } from './ensureParagraph';
import { hasSpacesOnly } from './hasSpacesOnly';
import { isWhiteSpacePreserved } from '../../domUtils/isWhiteSpacePreserved';
import type {
    ContentModelBlockGroup,
    ContentModelText,
    DomToModelContext,
} from 'roosterjs-content-model-types';
 
/**
 * Add a new text segment to current paragraph
 * @param group Current BlockGroup that the paragraph belong to
 * @param text Text content of the text segment
 * @param context Current DOM to Model context
 * @returns A new Text segment, or undefined if the input text is empty
 */
export function addTextSegment(
    group: ContentModelBlockGroup,
    text: string,
    context: DomToModelContext
): ContentModelText | undefined {
    let textModel: ContentModelText | undefined;
 
    if (text) {
        const paragraph = ensureParagraph(group, context.blockFormat);
 
        if (
            !hasSpacesOnly(text) ||
            (paragraph?.segments.length ?? 0) > 0 ||
            isWhiteSpacePreserved(paragraph?.format.whiteSpace)
        ) {
            textModel = createText(text, context.segmentFormat);
 
            if (context.isInSelection) {
                textModel.isSelected = true;
            }
 
            addDecorators(textModel, context);
 
            addSegment(group, textModel, context.blockFormat);
        }
    }
 
    return textModel;
}