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

100% Statements 56/56
95.31% Branches 61/64
100% Functions 13/13
100% Lines 52/52

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 1381x 1x 1x 1x 1x 1x                     1x 2323x   2323x 770x 770x   770x       47x 723x 191x       78x       13x       770x     2323x 2297x     2323x 2323x 2323x         770x     48x     1x         2323x 2032x 6x           2323x 2323x 250x 250x 250x   250x                       1x 1x             1x       2323x 2152x 2152x 2152x   2152x 6456x     2152x 433x                   6456x   6456x   1868x     1059x 1059x   5397x      
import { areSameFormats } from '../../domToModel/utils/areSameFormats';
import { createBr } from '../creators/createBr';
import { isSegmentEmpty } from './isEmpty';
import { isWhiteSpacePreserved } from '../../domUtils/isWhiteSpacePreserved';
import { mutateBlock, mutateSegment } from './mutate';
import { normalizeAllSegments } from './normalizeSegment';
import type {
    ContentModelSegmentFormat,
    ReadonlyContentModelParagraph,
    ReadonlyContentModelSegment,
} from 'roosterjs-content-model-types';
 
/**
 * @param paragraph The paragraph to normalize
 * Normalize a paragraph. If it is empty, add a BR segment to make sure it can insert content
 */
export function normalizeParagraph(paragraph: ReadonlyContentModelParagraph) {
    const segments = paragraph.segments;
 
    if (!paragraph.isImplicit && segments.length > 0) {
        const last = segments[segments.length - 1];
        const secondLast = segments[segments.length - 2];
 
        if (
            last.segmentType == 'SelectionMarker' &&
            (!secondLast || secondLast.segmentType == 'Br')
        ) {
            mutateBlock(paragraph).segments.push(createBr(last.format));
        } else if (segments.length > 1 && segments[segments.length - 1].segmentType == 'Br') {
            const noMarkerSegments = segments.filter(x => x.segmentType != 'SelectionMarker');
 
            // When there is content with a <BR> tag at the end, we can remove the BR.
            // But if there are more than one <BR> at the end, do not remove them.
            if (
                noMarkerSegments.length > 1 &&
                noMarkerSegments[noMarkerSegments.length - 2].segmentType != 'Br'
            ) {
                mutateBlock(paragraph).segments.pop();
            }
        }
 
        normalizeParagraphStyle(paragraph);
    }
 
    if (!isWhiteSpacePreserved(paragraph.format.whiteSpace)) {
        normalizeAllSegments(paragraph);
    }
 
    removeEmptyLinks(paragraph);
    removeEmptySegments(paragraph);
    moveUpSegmentFormat(paragraph);
}
 
function normalizeParagraphStyle(paragraph: ReadonlyContentModelParagraph) {
    // New paragraph should not have white-space style
    if (
        paragraph.format.whiteSpace &&
        paragraph.segments.every(
            seg => seg.segmentType == 'Br' || seg.segmentType == 'SelectionMarker'
        )
    ) {
        delete mutateBlock(paragraph).format.whiteSpace;
    }
}
 
function removeEmptySegments(block: ReadonlyContentModelParagraph) {
    for (let j = block.segments.length - 1; j >= 0; j--) {
        if (isSegmentEmpty(block.segments[j], true /*treatAnchorAsNotEmpty*/)) {
            mutateBlock(block).segments.splice(j, 1);
        }
    }
}
 
function removeEmptyLinks(paragraph: ReadonlyContentModelParagraph) {
    const marker = paragraph.segments.find(x => x.segmentType == 'SelectionMarker');
    if (marker) {
        const markerIndex = paragraph.segments.indexOf(marker);
        const prev = paragraph.segments[markerIndex - 1];
        const next = paragraph.segments[markerIndex + 1];
 
        if (
            (prev &&
                !prev.link &&
                areSameFormats(prev.format, marker.format) &&
                (!next || (!next.link && areSameFormats(next.format, marker.format))) &&
                marker.link) ||
            (!prev &&
                marker.link &&
                next &&
                !next.link &&
                areSameFormats(next.format, marker.format))
        ) {
            mutateSegment(paragraph, marker, mutableMarker => {
                delete mutableMarker.link;
            });
        }
    }
}
 
type FormatsToMoveUp = 'fontFamily' | 'fontSize' | 'textColor';
const formatsToMoveUp: FormatsToMoveUp[] = ['fontFamily', 'fontSize', 'textColor'];
 
// When all segments are sharing the same segment format (font name, size and color), we can move its format to paragraph
function moveUpSegmentFormat(paragraph: ReadonlyContentModelParagraph) {
    if (!paragraph.decorator) {
        const segments = paragraph.segments.filter(x => x.segmentType != 'SelectionMarker');
        const target = paragraph.segmentFormat || {};
        let changed = false;
 
        formatsToMoveUp.forEach(key => {
            changed = internalMoveUpSegmentFormat(segments, target, key) || changed;
        });
 
        if (changed) {
            mutateBlock(paragraph).segmentFormat = target;
        }
    }
}
 
function internalMoveUpSegmentFormat(
    segments: ReadonlyContentModelSegment[],
    target: ContentModelSegmentFormat,
    formatKey: FormatsToMoveUp
): boolean {
    const firstFormat = segments[0]?.format;
 
    if (
        firstFormat?.[formatKey] &&
        segments.every(segment => segment.format[formatKey] == firstFormat[formatKey]) &&
        target[formatKey] != firstFormat[formatKey]
    ) {
        target[formatKey] = firstFormat[formatKey];
        return true;
    } else {
        return false;
    }
}