All files / builder/platform/template-transform-strategy/wx-like wx-container.ts

97.14% Statements 102/105
93.6% Branches 117/125
96.66% Functions 29/30
97.11% Lines 101/104

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258                1x 1x                           1x 469x 469x     469x 469x     2196x 1028x 1168x 70x 1098x 825x 273x 30x 243x 243x             1311x       1028x 142x 30x           112x               1028x 1028x       1028x 10x   1018x         70x     30x     243x 243x 243x 243x 243x 21x       21x 21x 21x     222x 222x   243x 243x 254x   243x 222x           243x                     243x     825x       243x       226x                 1028x 142x   886x       1028x 1028x 1028x 1028x 1028x 110x   30x   1028x     101x                 10x   10x   1028x       190x   40x   1028x     311x   70x             1028x 1028x 317x 317x   1028x   30x     2730x             17x     243x 243x 222x   21x     469x 469x 448x 448x 21x 11x 11x 11x         10x 10x 10x         469x 243x 243x 243x 243x 243x 243x       469x      
import type {
  NgBoundTextMeta,
  NgContentMeta,
  NgElementMeta,
  NgNodeMeta,
  NgTemplateMeta,
  NgTextMeta,
} from '../../../mini-program-compiler';
import { MetaCollection } from '../../../mini-program-compiler';
import {
  isNgBoundTextMeta,
  isNgContentMeta,
  isNgElementMeta,
  isNgTemplateMeta,
  isNgTextMeta,
} from '../../util/type-predicate';
 
export interface WxContainerGlobalConfig {
  seq: string;
  directivePrefix: string;
  eventListConvert: (name: string[]) => string;
  templateInterpolation: [string, string];
}
export class WxContainer {
  private templateStr: string = '';
  private childContainerList: WxContainer[] = [];
  fromTemplate!: string;
  defineTemplateName!: string;
  private metaCollection: MetaCollection = new MetaCollection();
  constructor(private parent?: WxContainer) {}
 
  private _compileTemplate(node: NgNodeMeta): string {
    if (isNgElementMeta(node)) {
      return this.ngElementTransform(node);
    } else if (isNgBoundTextMeta(node)) {
      return this.ngBoundTextTransform(node);
    } else if (isNgTextMeta(node)) {
      return this.ngTextTransform(node);
    } else if (isNgContentMeta(node)) {
      return this.ngContentTransform(node);
    } else Eif (isNgTemplateMeta(node)) {
      return this.ngTemplateTransform(node);
    } else {
      throw new Error('未知的ng节点元数据');
    }
  }
 
  compileNode(node: NgNodeMeta) {
    this.templateStr += this._compileTemplate(node);
  }
 
  private ngElementTransform(node: NgElementMeta): string {
    if (node.componentMeta) {
      if (node.componentMeta.exportPath) {
        this.metaCollection.libraryPath.add({
          selector: node.componentMeta.selector,
          path: node.componentMeta.exportPath,
          className: node.componentMeta.className,
        });
      } else {
        this.metaCollection.localPath.add({
          path: node.componentMeta.filePath,
          selector: node.componentMeta.selector,
          className: node.componentMeta.className,
        });
      }
    }
 
    const children = node.children.map((child) => this._compileTemplate(child));
    const commonTagProperty = `${this.setComponentIdentification(
      node.componentMeta?.isComponent,
      node.index
    )} ${this.elementPropertyAndEvent(node, node.index).join(' ')}`;
    if (node.singleClosedTag) {
      return `<${node.tagName} ${commonTagProperty}/>`;
    }
    return `<${node.tagName} ${
      node.tagName === 'block' ? '' : commonTagProperty
    }>${children.join('')}</${node.tagName}>`;
  }
  private ngBoundTextTransform(node: NgBoundTextMeta): string {
    return `{{nodeList[${node.index}].value}}`;
  }
  private ngContentTransform(node: NgContentMeta): string {
    return node.name ? `<slot name="${node.name}"></slot>` : `<slot></slot>`;
  }
  private ngTemplateTransform(node: NgTemplateMeta): string {
    let content = '';
    const defineTemplateName = node.defineTemplateName;
    const childContainer = new WxContainer(this);
    const globalTemplate = this.isGlobalTemplate(node.defineTemplateName);
    if (globalTemplate) {
      Iif (this.fromTemplate && this.fromTemplate !== globalTemplate) {
        throw new Error(
          `全局ng-template中不可包含其他位置的ng-template,当前为${this.fromTemplate},包含${globalTemplate}`
        );
      } else Eif (globalTemplate) {
        childContainer.fromTemplate = globalTemplate;
        childContainer.defineTemplateName = defineTemplateName;
      }
    } else {
      childContainer.fromTemplate = this.fromTemplate;
      childContainer.defineTemplateName = defineTemplateName;
    }
    this.childContainerList.push(childContainer);
    node.children.forEach((childNode) => {
      childContainer.compileNode(childNode);
    });
    if (this.fromTemplate === childContainer.fromTemplate) {
      this.metaCollection.templateList.push({
        name: defineTemplateName,
        content: `<template name="${defineTemplateName}">${childContainer.templateStr}</template>`,
      });
    }
 
    content += `<block ${WxContainer.globalConfig.directivePrefix}${
      WxContainer.globalConfig.seq
    }for="{{nodeList[${node.index}]}}" ${
      WxContainer.globalConfig.directivePrefix
    }${WxContainer.globalConfig.seq}key="index">
      <template is="{{item.__templateName||'${defineTemplateName}'}}" ${this.getTemplateDataStr(
      node.index,
      `index`
    )}></template>
      </block>`;
 
    return content;
  }
  private ngTextTransform(node: NgTextMeta): string {
    return `${node.value}`;
  }
 
  private getTemplateDataStr(directiveIndex: number, indexName: string) {
    return `data="${WxContainer.globalConfig.templateInterpolation[0]}...nodeList[${directiveIndex}][${indexName}] ${WxContainer.globalConfig.templateInterpolation[1]}"`;
  }
 
  export(): { wxmlTemplate: string } {
    return {
      wxmlTemplate: this.templateStr,
    };
  }
 
  private setComponentIdentification(
    isComponent: boolean | undefined,
    nodeIndex: number | undefined
  ) {
    if (isComponent) {
      return `nodePath="{{nodePath}}" nodeIndex="${nodeIndex}"`;
    }
    return ``;
  }
 
  private elementPropertyAndEvent(node: NgElementMeta, index: number) {
    const propertyMap = new Map<string, string>();
    const attributeMap = new Map<string, string>();
    propertyMap.set('class', `nodeList[${index}].class`);
    propertyMap.set('style', `nodeList[${index}].style`);
    Object.entries(node.attributes)
      .filter(([key, value]) => value !== '')
      .forEach(([key, value]) => {
        attributeMap.set(key, value);
      });
    node.inputs
      .filter(
        (property) =>
          !(
            (node.componentMeta?.inputs?.includes(property) ||
              node.directiveMeta?.inputs?.includes(property)) &&
            !(
              node.directiveMeta?.properties?.includes(property) ||
              node.componentMeta?.properties?.includes(property)
            )
          )
      )
      .filter((key) => !/^(class\.?|style\.?)/.test(key))
      .forEach((key) => {
        propertyMap.set(key, `nodeList[${index!}].property.${key}`);
      });
    [
      ...(node.directiveMeta?.properties || []),
      ...(node.componentMeta?.properties || []),
    ]
      .filter((key) => !/^(class\.?|style\.?)/.test(key))
      .forEach((key) => {
        propertyMap.set(key, `nodeList[${index!}].property.${key}`);
      });
    const eventList: string[] = [
      ...node.outputs.filter(
        (item) =>
          !(
            node.componentMeta?.outputs.some((output) => output === item) ||
            node.directiveMeta?.outputs.some((output) => output === item)
          )
      ),
      ...(node.directiveMeta?.listeners || []),
      ...(node.componentMeta?.isComponent ? node.componentMeta.listeners : []),
    ];
 
    const result = WxContainer.globalConfig.eventListConvert(eventList);
    if (result) {
      propertyMap.set(`data-node-path`, `nodePath`);
      propertyMap.set(`data-node-index`, `${index}`);
    }
    return [
      ...Array.from(attributeMap.entries()).map(
        ([key, value]) => `${key}="${value}"`
      ),
      ...Array.from(propertyMap.entries()).map(
        ([key, value]) => `${key}="{{${value}}}"`
      ),
      result,
    ];
  }
  static globalConfig: WxContainerGlobalConfig;
  static initWxContainerFactory(globalConfig: WxContainerGlobalConfig) {
    this.globalConfig = globalConfig;
  }
  private isGlobalTemplate(name: string) {
    const result = name.match(/^\$\$mp\$\$([^$]+)\$\$(.*)/);
    if (!result) {
      return undefined;
    }
    return result[1];
  }
  exportMetaCollectionGroup() {
    const obj: Record<string, MetaCollection> = {};
    if (!this.fromTemplate) {
      obj.$inline = obj.$inline || new MetaCollection();
      obj.$inline.merge(this.metaCollection);
    } else if (this.fromTemplate == '__self__') {
      obj.$self = obj.$self || new MetaCollection();
      obj.$self.merge(this.metaCollection);
      obj.$self.templateList.push({
        name: this.defineTemplateName,
        content: `<template name="${this.defineTemplateName}">${this.templateStr}</template>`,
      });
    } else {
      obj[this.fromTemplate] = obj[this.fromTemplate] || new MetaCollection();
      obj[this.fromTemplate].merge(this.metaCollection);
      obj[this.fromTemplate].templateList.push({
        name: this.defineTemplateName,
        content: `<template name="${this.defineTemplateName}">${this.templateStr}</template>`,
      });
    }
    this.childContainerList.forEach((container) => {
      const result = container.exportMetaCollectionGroup();
      for (const key in result) {
        Eif (Object.prototype.hasOwnProperty.call(result, key)) {
          const element = result[key];
          obj[key] = obj[key] || new MetaCollection();
          obj[key].merge(element);
        }
      }
    });
    return obj;
  }
}