All files / roosterjs-content-model-markdown/lib/publicApi isContentMarkdown.ts

100% Statements 23/23
100% Branches 8/8
100% Functions 1/1
100% Lines 14/14

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  1x                   1x                             1x 49x 2x     47x   50x 178x 178x 29x         73x 73x 8x       10x    
// Block-level markdown patterns. A line that matches any of these is considered markdown.
const BlockPatterns: RegExp[] = [
    /^#{1,6}\s.+/, // heading: "# text" .. "###### text"
    /^\s*>\s.+/, // blockquote: "> text"
    /^\s*[\*\-\+]\s.+/, // unordered list: "- item", "* item", "+ item"
    /^\s*\d+\.\s.+/, // ordered list: "1. item"
    /^---+$/, // horizontal rule: "---"
    /^\s*\|.*\|\s*$/, // table row: "| a | b |"
];
 
// Inline markdown patterns. The text contains markdown if any of these match anywhere.
const InlinePatterns: RegExp[] = [
    /!\[[^\[\]]+\]\([^\)\s]+\)/, // image: ![alt](url)
    /\[[^\[\]]+\]\([^\)\s]+\)/, // link: [text](url)
    /\*\*[^\s*][^*]*\*\*/, // bold: **text**
    /(^|[^*])\*[^\s*][^*]*\*([^*]|$)/, // italic: *text* (not part of **)
    /~~[^\s~][^~]*~~/, // strikethrough: ~~text~~
];
 
/**
 * Detect whether the given plain text contains any markdown markup.
 * Recognizes block-level patterns (headings, blockquotes, lists, horizontal rules, tables)
 * and inline patterns (bold, italic, strikethrough, links, images).
 * @param text The plain text to check.
 * @returns True if the text contains any markdown markup, false otherwise.
 */
export function isContentMarkdown(text: string): boolean {
    if (!text || !text.trim()) {
        return false;
    }
 
    const lines = text.split(/\r\n|\r|\n/);
 
    for (const line of lines) {
        for (const pattern of BlockPatterns) {
            if (pattern.test(line)) {
                return true;
            }
        }
    }
 
    for (const pattern of InlinePatterns) {
        if (pattern.test(text)) {
            return true;
        }
    }
 
    return false;
}