All files / roosterjs-content-model-markdown/lib/modelToMarkdown/creators createMarkdownParagraph.ts

96.97% Statements 32/33
91.67% Branches 22/24
100% Functions 2/2
96.67% Lines 29/30

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 651x                         1x       84x 84x 109x 109x   100x 100x   7x 7x   2x 1x   2x           84x 9x 9x 9x 8x       84x       100x 100x 10x   100x 3x   100x 1x   100x 4x   100x    
import { MarkdownHeadings } from '../../constants/headings';
import type { ContentModelParagraph, ContentModelText } from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
export interface ParagraphContext {
    ignoreLineBreaks: boolean;
}
 
/**
 * @internal
 */
export function createMarkdownParagraph(
    paragraph: ContentModelParagraph,
    context?: ParagraphContext
): string {
    const { segments } = paragraph;
    let markdownString = '';
    for (const segment of segments) {
        switch (segment.segmentType) {
            case 'Text':
                markdownString += textProcessor(segment);
                break;
            case 'Image':
                markdownString += `![${segment.alt || 'image'}](${segment.src})`;
                break;
            case 'Br':
                if (!context?.ignoreLineBreaks) {
                    markdownString += '\n';
                }
                break;
            default:
                break;
        }
    }
 
    if (paragraph.decorator) {
        const { tagName } = paragraph.decorator;
        const prefix = MarkdownHeadings[tagName];
        if (prefix) {
            markdownString = `${prefix}${markdownString}`;
        }
    }
 
    return markdownString;
}
 
function textProcessor(text: ContentModelText): string {
    let markdownString = text.text;
    if (text.link) {
        markdownString = `[${text.text}](${text.link.format.href})`;
    }
    if (text.format.fontWeight == 'bold') {
        markdownString = `**${markdownString}**`;
    }
    if (text.format.strikethrough) {
        markdownString = `~~${markdownString}~~`;
    }
    if (text.format.italic) {
        markdownString = `*${markdownString}*`;
    }
    return markdownString;
}