All files / roosterjs-content-model-markdown/lib/markdownToModel/utils splitParagraphSegments.ts

95.24% Statements 20/21
81.25% Branches 13/16
100% Functions 2/2
95.24% Lines 20/21

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 571x                     1x 26x 26x 26x                 1x 181x 181x 181x   181x 26x 19x     26x 14x         12x 12x             26x     181x 165x     181x    
const linkRegex = /(\[([^\[]+)\]\((https?:\/\/[^\)]+)\))|(\!\[([^\[]+)\]\((https?:\/\/[^\)]+)\))/g;
 
/**
 * @internal
 */
interface MarkdownSegment {
    text: string;
    url: string;
    type: 'text' | 'link' | 'image';
}
 
const isValidUrl = (url: string) => {
    try {
        new URL(url);
        return true;
    } catch (_) {
        return false;
    }
};
 
/**
 * @internal
 */
export function splitParagraphSegments(text: string): MarkdownSegment[] {
    const result: MarkdownSegment[] = [];
    let lastIndex = 0;
    let match: RegExpExecArray | null = null;
 
    while ((match = linkRegex.exec(text)) !== null) {
        if (match.index > lastIndex) {
            result.push({ type: 'text', text: text.slice(lastIndex, match.index), url: '' });
        }
 
        if (match[2] && match[3]) {
            result.push(
                isValidUrl(match[3])
                    ? { type: 'link', text: match[2], url: match[3] }
                    : { type: 'text', text: match[0], url: '' }
            );
        } else Eif (match[5] && match[6]) {
            result.push(
                isValidUrl(match[6])
                    ? { type: 'image', text: match[5], url: match[6] }
                    : { type: 'text', text: match[0], url: '' }
            );
        }
 
        lastIndex = linkRegex.lastIndex;
    }
 
    if (lastIndex < text.length) {
        result.push({ type: 'text', text: text.slice(lastIndex), url: '' });
    }
 
    return result;
}