All files / builder/component-template-inject change-component.ts

100% Statements 27/27
100% Branches 6/6
100% Functions 1/1
100% Lines 27/27

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 731x           1x 1x   1x 719x 719x   719x     719x 493x   226x 226x 258x   258x       258x       258x 34x   224x     224x     224x     224x       224x 224x 121x 121x           103x           224x   226x                
import {
  Change,
  InsertChange,
  TsChange,
  createCssSelectorForTs,
} from 'cyia-code-util';
import * as ts from 'typescript';
import { RawUpdater } from '../util';
 
export function changeComponent(data: string) {
  const sf = ts.createSourceFile('', data, ts.ScriptTarget.Latest, true);
  const selector = createCssSelectorForTs(sf);
 
  const ɵcmpNodeList = selector.queryAll(
    `PropertyAccessExpression[name=ɵɵdefineComponent]~SyntaxList ObjectLiteralExpression`
  ) as ts.BinaryExpression[];
  if (!ɵcmpNodeList.length) {
    return undefined;
  }
  const changeList: Change[] = [];
  for (const componentNode of ɵcmpNodeList) {
    const ɵcmpNode = componentNode;
 
    const templateNode = selector.queryOne(
      ɵcmpNode,
      `PropertyAssignment[name=template]::initializer`
    ) as ts.PropertyAssignment;
    const initIfNode = selector.queryOne(
      templateNode,
      `IfStatement[expression="rf & 1"]`
    ) as ts.IfStatement;
    if (!initIfNode) {
      continue;
    }
    const change = new TsChange(sf);
 
    let updateInsertChange: InsertChange;
    changeList.push(
      new InsertChange(0, `import * as amp from 'angular-miniprogram';\n`)
    );
    changeList.push(
      new InsertChange(0, `import * as ampNgCore from '@angular/core';\n`)
    );
    const updateIfNode = selector.queryOne(
      templateNode,
      `IfStatement[expression="rf & 2"]`
    ) as ts.IfStatement;
    const updateContent = `amp.propertyChange(ampNgCore.ɵɵgetCurrentView());`;
    if (updateIfNode) {
      const updateBlock = updateIfNode.thenStatement as ts.Block;
      updateInsertChange = change.insertNode(
        updateBlock.statements[updateBlock.statements.length - 1],
        `;${updateContent}`,
        'end'
      );
    } else {
      updateInsertChange = change.insertNode(
        initIfNode,
        `if(rf & 2){${updateContent}}`,
        'end'
      );
    }
    changeList.push(updateInsertChange);
  }
  return {
    content: RawUpdater.update(data, changeList),
    // todo library可否支持同文件多组件
    componentName: selector
      .queryOne(ɵcmpNodeList[0], 'PropertyAssignment[name=type]::initializer')
      .getText(),
  };
}