All files / src/renderer createNodes.ts

100% Statements 17/17
100% Branches 0/0
100% Functions 4/4
100% Lines 16/16

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                19x         190x   190x   190x       190x     190x   190x     190x     190x   190x   190x                     190x   395x                               395x   555x     395x    
import { NodePatcherRule } from "./createNodePatcherRules";
import { CompiledNodePatcherRule, NodePatchingData } from "./NodePatcher";
 
/**
 * Creates the nodes to be appended to the parent one according to the patching data 
 * @param patchingData The patching data to create the nodes from
 * @returns The list of the created nodes
 */
 export default function createNodes(patchingData: NodePatchingData): Node {
 
    const {
        patcher,
        values
    } = patchingData;
 
    const doc = patcher.template.content.cloneNode(/*deep*/true); // The content of the template is a document fragment
 
    const rules = compileRules(doc, patcher.rules);
 
    const {
        childNodes
    } = doc;
 
     // Set the first node as holder of the patching data
    const node = childNodes[0];
 
    patchingData.node = node;
 
    // Attach the patching data to the node
    (node as any)._$patchingData = patchingData;
 
    // Update the rules of the patching data
    patchingData.rules = rules;
 
    patcher.firstPatch(doc, rules, values);
 
    return doc; // Return the DocumentFragment to its children can efficiently transferred to the container
}
 
/**
 * Creates a compiled rule by replacing the path with the reference to the node the rule acts upon
 * @param node The content node of the template
 * @param rules The rules to compile
 * @returns the compiled rules
 */
 function compileRules(node: Node, rules: NodePatcherRule[]): CompiledNodePatcherRule[] {
 
    return rules.map(r => {
 
        return {
            node: findNode(node, r.path),
            type: r.type,
            name: r.name
        };
    });
}
 
/**
 * Finds the child node following the path
 * @param node The parent node
 * @param path The path to the child node
 * @returns The child node
 */
function findNode(node: Node, path: number[]): HTMLElement | Comment | Text {
 
    for (let i = 0; i < path.length; ++i) {
 
        node = node.childNodes[path[i]];
    }
 
    return node as HTMLElement | Comment | Text;
}