All files / virtual-dom markupToVirtualNode.ts

95.24% Statements 20/21
71.43% Branches 10/14
100% Functions 4/4
95% Lines 19/20

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 596x 6x 6x 6x 6x                 6x           28x   28x         28x   44x         28x   5x 5x             27x   1x   1x   5x         26x     27x  
import FragmentNode from "./nodes/FragmentNode";
import parseFromString from "./helpers/parseFromString";
import nodeToVirtualNode from "./helpers/nodeToVirtualNode";
import MarkupParsingResult from "./MarkupParsingResult";
import { isBlankOrWhiteSpace } from "../utils/string";
 
/**
 * Convert a HTML markup into a virtual node
 * @param markup 
 * @param type 
 * @param options 
 * @returns 
 */
export default function markupToVirtualNode(
    markup: string,
    type: 'html' | 'xml' = 'xml',
    options: any = {}
): MarkupParsingResult {
 
    let nodes = Array.from(parseFromString(markup, type));
 
    Iif (nodes === null) {
 
        return null;
    }
 
    Eif (options.excludeTextWithWhiteSpacesOnly === true) {
 
        nodes = nodes.filter(node => node instanceof HTMLElement ||
            node instanceof Comment ||
            node instanceof Text && !isBlankOrWhiteSpace((node as Text).textContent)) // Exclude text with white spaces
    }
 
    const vnode = nodes.length > 1 ?
        new FragmentNode(
            nodes.map(n => nodeToVirtualNode(n, options))
                .filter(n => n !== null)
        ) :
        nodeToVirtualNode(nodes[0], options);
 
    // Wrap the nodes in a fragment if more than one
    let node: Node | DocumentFragment;
 
    if (nodes.length > 1) {
 
        node = new DocumentFragment();
 
        for (const n of nodes) {
 
            node.appendChild(n);
        }
    }
    else {
 
        node = nodes[0];
    }
 
    return new MarkupParsingResult(vnode, node);
}