All files / roosterjs-content-model-markdown/lib/markdownToModel/appliers applyTextFormatting.ts

100% Statements 26/26
100% Branches 12/12
100% Functions 4/4
100% Lines 22/22

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 471x             1x         1x 243x 243x 265x 265x   243x       297x               265x 7x 7x 7x 258x 10x 10x 10x 248x 10x 10x 10x     265x    
import { createText } from 'roosterjs-content-model-dom';
import type {
    ContentModelLink,
    ContentModelSegmentFormat,
    ContentModelText,
} from 'roosterjs-content-model-types';
 
const SPLIT_PATTERN = /(\*\*\*.*?\*\*\*|\*\*.*?\*\*|\*.*?\*)/;
 
/**
 * @internal
 */
export function applyTextFormatting(textSegment: ContentModelText) {
    const texts = splitSegments(textSegment.text);
    const textSegments: ContentModelText[] = [];
    for (const text of texts) {
        textSegments.push(createFormattedSegment(text, textSegment.format, textSegment.link));
    }
    return textSegments;
}
 
function splitSegments(text: string): string[] {
    return text.split(SPLIT_PATTERN).filter(s => s.trim().length > 0);
}
 
function createFormattedSegment(
    text: string,
    format: ContentModelSegmentFormat,
    link?: ContentModelLink
): ContentModelText {
    if (text.startsWith('***') && text.endsWith('***')) {
        format = { ...format, fontWeight: 'bold', italic: true };
        text = text.replace(/\*\*\*/g, '');
        text = text + ' ';
    } else if (text.startsWith('**') && text.endsWith('**')) {
        format = { ...format, fontWeight: 'bold' };
        text = text.replace(/\*\*/g, '');
        text = text + ' ';
    } else if (text.startsWith('*') && text.endsWith('*')) {
        format = { ...format, italic: true };
        text = text.replace(/\*/g, '');
        text = text + ' ';
    }
 
    return createText(text, format, link);
}