All files / roosterjs-content-model-api/lib/publicApi/segment setBackgroundColor.ts

100% Statements 17/17
93.33% Branches 14/15
100% Functions 3/3
100% Lines 17/17

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 451x 1x               1x 8x   8x 8x   8x       8x 1x   7x     8x 7x 7x           8x 5x       5x 5x          
import { createSelectionMarker, setSelection } from 'roosterjs-content-model-dom';
import { formatSegmentWithContentModel } from '../utils/formatSegmentWithContentModel';
import type { IEditor, ShallowMutableContentModelParagraph } from 'roosterjs-content-model-types';
 
/**
 * Set background color
 * @param editor The editor to operate on
 * @param backgroundColor The color to set. Pass null to remove existing color.
 */
export function setBackgroundColor(editor: IEditor, backgroundColor: string | null) {
    editor.focus();
 
    let lastParagraph: ShallowMutableContentModelParagraph | null = null;
    let lastSegmentIndex: number = -1;
 
    formatSegmentWithContentModel(
        editor,
        'setBackgroundColor',
        (format, _, segment, paragraph) => {
            if (backgroundColor === null) {
                delete format.backgroundColor;
            } else {
                format.backgroundColor = backgroundColor;
            }
 
            if (segment && paragraph && segment.segmentType != 'SelectionMarker') {
                lastParagraph = paragraph;
                lastSegmentIndex = lastParagraph.segments.indexOf(segment);
            }
        },
        undefined /*segmentHasStyleCallback*/,
        undefined /*includingFormatHolder*/,
        model => {
            if (lastParagraph && lastSegmentIndex >= 0) {
                const marker = createSelectionMarker(
                    lastParagraph.segments[lastSegmentIndex]?.format
                );
 
                lastParagraph.segments.splice(lastSegmentIndex + 1, 0, marker);
                setSelection(model, marker, marker);
            }
        }
    );
}