All files / roosterjs-content-model-markdown/lib/markdownToModel/creators createListFromMarkdown.ts

100% Statements 23/23
100% Branches 14/14
100% Functions 4/4
100% Lines 23/23

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 551x 1x             1x         45x 45x 45x 45x 45x 45x 45x 1x     45x 45x                 45x       45x 1x   45x 45x 10x   45x       45x     1x 45x    
import { createListItem, createListLevel } from 'roosterjs-content-model-dom';
import { createParagraphFromMarkdown } from './createParagraphFromMarkdown';
import type { ContentModelListItem } from 'roosterjs-content-model-types';
import type { MarkdownToModelOptions } from '../types/MarkdownToModelOptions';
 
/**
 * @internal
 */
export function createListFromMarkdown(
    text: string,
    listType: 'OL' | 'UL',
    options: MarkdownToModelOptions
): ContentModelListItem {
    const marker = text.trim().split(' ')[0];
    const isDummy = isDummyListItem(marker);
    const itemText = isDummy ? text : text.trim().substring(marker.length);
    const paragraph = createParagraphFromMarkdown(itemText.trim(), options);
    const levels = createLevels(text, listType, isDummy, options);
    const listModel = createListItem(levels);
    if (options.direction) {
        listModel.format.direction = options.direction;
    }
 
    listModel.blocks.push(paragraph);
    return listModel;
}
 
function createLevels(
    text: string,
    listType: 'OL' | 'UL',
    isDummy: boolean,
    options: MarkdownToModelOptions
) {
    const level = createListLevel(
        listType,
        options.direction ? { direction: options.direction } : undefined
    );
    if (isDummy) {
        level.format.displayForDummyItem = 'block';
    }
    const levels = [level];
    if (isSubListItem(text)) {
        levels.push(level);
    }
    return levels;
}
 
function isSubListItem(item: string): boolean {
    return item.startsWith(' ');
}
 
const isDummyListItem = (item: string) => {
    return item != '-' && item != '+' && item != '*' && !item.endsWith('.');
};