All files / roosterjs-content-model-dom/lib/modelApi/editing getSegmentTextFormat.ts

100% Statements 11/11
91.67% Branches 11/12
100% Functions 3/3
100% Lines 11/11

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                      1x       337x 337x                       337x     1x 337x 337x 3033x   3033x 107x     337x    
import type {
    ContentModelSegmentFormat,
    ReadonlyContentModelSegment,
} from 'roosterjs-content-model-types';
 
/**
 * Get the text format of a segment, this function will return only format that is applicable to text
 * @param segment The segment to get format from
 * @param includingBIU When pass true, also get Bold/Italic/Underline format
 * @returns
 */
export function getSegmentTextFormat(
    segment: ReadonlyContentModelSegment,
    includingBIU?: boolean
): ContentModelSegmentFormat {
    const format = segment.format ?? {};
    const textFormat: ContentModelSegmentFormat = {
        fontFamily: format.fontFamily,
        fontSize: format.fontSize,
        textColor: format.textColor,
        backgroundColor: format.backgroundColor,
        letterSpacing: format.letterSpacing,
        lineHeight: format.lineHeight,
        fontWeight: includingBIU ? format.fontWeight : undefined,
        italic: includingBIU ? format.italic : undefined,
        underline: includingBIU ? format.underline : undefined,
    };
 
    return removeUndefinedValues(textFormat);
}
 
const removeUndefinedValues = (format: ContentModelSegmentFormat): ContentModelSegmentFormat => {
    const textFormat: Record<string, string | undefined | boolean | never[]> = {};
    Object.keys(format).filter(key => {
        const value = format[key as keyof ContentModelSegmentFormat];
 
        if (value !== undefined) {
            textFormat[key] = value;
        }
    });
    return textFormat;
};