All files / roosterjs-content-model-core/lib/command/createModelFromHtml createModelFromHtml.ts

100% Statements 13/13
90% Branches 9/10
100% Functions 1/1
100% Lines 13/13

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 441x 1x 1x 1x                             1x           6x   6x 4x           4x   4x 4x   4x   2x      
import { convertInlineCss, retrieveCssRules } from './convertInlineCss';
import { createDOMCreator } from '../../utils/domCreator';
import { createDomToModelContextForSanitizing } from './createDomToModelContextForSanitizing';
import { createEmptyModel, domToContentModel, parseFormat } from 'roosterjs-content-model-dom';
import type {
    ContentModelDocument,
    ContentModelSegmentFormat,
    DomToModelOptionForSanitizing,
    TrustedHTMLHandler,
} from 'roosterjs-content-model-types';
 
/**
 * Create Content Model from HTML string
 * @param html The source HTML string
 * @param options Options for DOM to Content Model conversion
 * @param trustedHTMLHandler A string handler to convert string to trusted string
 * @returns A Content Model Document object that contains the Content Model from the give HTML, or undefined if failed to parse the source HTML
 */
export function createModelFromHtml(
    html: string,
    options?: Partial<DomToModelOptionForSanitizing>,
    trustedHTMLHandler?: TrustedHTMLHandler,
    defaultSegmentFormat?: ContentModelSegmentFormat
): ContentModelDocument {
    const doc = html ? createDOMCreator(trustedHTMLHandler).htmlToDOM(html) : null;
 
    if (doc?.body) {
        const context = createDomToModelContextForSanitizing(
            doc,
            defaultSegmentFormat,
            undefined /*defaultOptions*/,
            options
        );
        const cssRules = doc ? retrieveCssRules(doc) : [];
 
        convertInlineCss(doc, cssRules);
        parseFormat(doc.body, context.formatParsers.segmentOnBlock, context.segmentFormat, context);
 
        return domToContentModel(doc.body, context);
    } else {
        return createEmptyModel(defaultSegmentFormat);
    }
}