All files / lib/pipeline/module/compiler importModule.ts

100% Statements 16/16
87.5% Branches 7/8
100% Functions 3/3
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  26x         26x     1587x   3x   1584x   8x             3x     3x           3x 3x         8x     8x 8x     8x 8x 8x  
import { HtmlCompilerModule, HtmlCompilerContext } from '../htmlCompiler';
import { MImportNode, TagNode, MFragmentNode } from '../../..';
 
/**
 * Process imports / aliases via m-import
 */
export class ImportModule implements HtmlCompilerModule {
    enterNode(htmlContext: HtmlCompilerContext): void {
        
        if (MImportNode.isMImportNode(htmlContext.node)) {
            // if this is m-import, then process it
            registerImport(htmlContext.node, htmlContext);
 
        } else if (TagNode.isTagNode(htmlContext.node) && htmlContext.hasImport(htmlContext.node.tagName)) {
            // else if this is a replacement node, then replace it
            replaceImport(htmlContext.node, htmlContext);
        }
    }
}
 
function registerImport(mImport: MImportNode, htmlContext: HtmlCompilerContext): void {
    // imports are registered into the parent scope. Fall back to current scope in case this is the root
    const targetNodeData = htmlContext.parentContext ?? htmlContext;
 
    // create import definition and register in compile data
    targetNodeData.defineImport({
        alias: mImport.as,
        source: mImport.src
    });
 
    // delete node
    mImport.removeSelf();
    htmlContext.setDeleted();
}
 
function replaceImport(tag: TagNode, htmlContext: HtmlCompilerContext): void {
    // get import definition
    const importDefinition = htmlContext.getImport(tag.tagName);
 
    // create replacement
    const attributes = new Map(tag.getAttributes().entries());
    const replacementTag = new MFragmentNode(importDefinition.source, attributes);
 
    // replace tag
    replacementTag.appendChildren(tag.childNodes);
    tag.replaceSelf([ replacementTag ]);
    htmlContext.setDeleted();
}