visitor.js 7.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
const t = require('@babel/types')

const {
  METHOD_CREATE_ELEMENT,
  METHOD_TO_STRING,
  METHOD_RENDER_LIST,
  METHOD_BUILT_IN,
  METHOD_RESOLVE_FILTER,
  IDENTIFIER_FILTER,
  IDENTIFIER_METHOD,
  IDENTIFIER_GLOBAL
} = require('../../constants')

const {
  getTagName
} = require('../../h5')

const {
  hyphenate,
20
  traverseFilter,
fxy060608's avatar
fxy060608 已提交
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
  getComponentName
} = require('../../util')

const traverseData = require('./data')
const traverseRenderList = require('./render-list')

const getMemberExpr = require('./member-expr')

function addStaticClass (path, staticClass) {
  const dataPath = path.get('arguments.1')
  if (dataPath && dataPath.isObjectExpression()) {
    const staticClassProperty = dataPath.node.properties.find(property => property.key.name === 'staticClass')
    if (staticClassProperty) { // update
      staticClassProperty.value.value = staticClassProperty.value.value + ' ' + staticClass
    } else { // add
      dataPath.node.properties.push(
        t.objectProperty(t.identifier('staticClass'), t.stringLiteral(staticClass))
      )
    }
  } else { // {staticClass:'data-v-aaa'}
    const args = path.node.arguments
    args.splice(1, 0, t.objectExpression(
      [
        t.objectProperty(t.identifier('staticClass'), t.stringLiteral(staticClass))
      ]
    ))
  }
}

function addVueId (path, state) {
  // const platformName = state.options.platform.name
  // if ( // 暂不对 mp-weixin,app-plus 增加 vueId
  //   platformName === 'mp-weixin' ||
  //       platformName === 'app-plus'
  // ) {
  //   return
  // }
  if (!state.options.hasOwnProperty('$vueId')) {
    state.options.$vueId = 1
  }
fxy060608's avatar
fxy060608 已提交
61
  const hashId = state.options.hashId
62
  const vueId = (hashId ? (hashId + '-') : '') + (state.options.$vueId++)
fxy060608's avatar
fxy060608 已提交
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

  let value

  if (state.scoped.length) {
    let scopeds = state.scoped
    let len = scopeds.length
    if (len > 1) { // v-for 嵌套,forIndex 不允许重复
      const forIndexSet = new Set()
      for (let i = 0; i < len; i++) {
        const scoped = scopeds[i]
        forIndexSet.add(scoped.forIndex)
        if (forIndexSet.size !== i + 1) {
          state.errors.add(`v-for 嵌套时,索引名称 ${scoped.forIndex} 不允许重复`)
          break
        }
      }
    }
    for (let i = len - 1; i >= 0; i--) {
      const scoped = scopeds[i]
      if (!value) {
        value = t.binaryExpression('+', t.stringLiteral(vueId + '-'), t.identifier(scoped.forIndex))
      } else {
        value = t.binaryExpression('+',
          t.binaryExpression('+', value, t.stringLiteral('-')),
          t.identifier(scoped.forIndex)
        )
      }
    }
  } else {
    value = t.stringLiteral(vueId)
  }

  const objectProperty = t.objectProperty(
    t.stringLiteral('vue-id'),
    value
  )

  const dataPath = path.get('arguments.1')
  if (dataPath && dataPath.isObjectExpression()) {
    const attrsProperty = dataPath.node.properties.find(property => property.key.name === 'attrs')
    if (attrsProperty) {
      attrsProperty.value.properties.unshift(objectProperty)
    } else {
      dataPath.node.properties.push(
        t.objectProperty(t.identifier('attrs'), t.objectExpression([
          objectProperty
        ]))
      )
    }
  } else { // {attrs:{'vue-id':'2'}}
    const args = path.node.arguments
    args.splice(1, 0, t.objectExpression(
      [
        t.objectProperty(t.identifier('attrs'), t.objectExpression([
          objectProperty
        ]))
      ]
    ))
  }
}

function checkUsingGlobalComponents (name, globalUsingComponents, state) {
  if (globalUsingComponents && globalUsingComponents[name]) {
    if (!state.options.usingGlobalComponents) {
      state.options.usingGlobalComponents = Object.create(null)
    }
    state.options.usingGlobalComponents[name] = globalUsingComponents[name]
  }
}

module.exports = {
  noScope: true,
135 136 137 138 139 140 141 142
  MemberExpression (path) {
    if ( // t.m(123)
      t.isIdentifier(path.node.object) &&
      this.options.filterModules.includes(path.node.object.name)
    ) {
      path.skip()
    }
  },
fxy060608's avatar
fxy060608 已提交
143 144
  CallExpression (path) {
    const callee = path.node.callee
145 146 147
    if (traverseFilter(callee, this)) {
      return path.skip()
    } else if (t.isIdentifier(callee)) {
fxy060608's avatar
fxy060608 已提交
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
      const methodName = callee.name
      switch (methodName) {
        case METHOD_CREATE_ELEMENT:
          const tagNode = path.node.arguments[0]
          if (t.isStringLiteral(tagNode)) {
            // 需要把标签增加到 class 样式中
            const tagName = getTagName(tagNode.value)
            if (tagName !== tagNode.value) {
              addStaticClass(path, '_' + tagNode.value)
            }
            tagNode.value = getComponentName(hyphenate(tagName))

            // 组件增加 vueId
            if (this.options.platform.isComponent(tagNode.value)) {
              addVueId(path, this)
            }

            // 查找全局组件
            checkUsingGlobalComponents(
              tagNode.value,
              this.options.globalUsingComponents,
              this
            )
          }
          if (this.options.scopeId) {
            addStaticClass(path, this.options.scopeId)
          }

          const dataPath = path.get('arguments.1')
          dataPath && dataPath.isObjectExpression() && traverseData(dataPath, this, tagNode.value)
          break
        case METHOD_TO_STRING:
          const stringNodes = path.node.arguments[0]
          stringNodes.$toString = true
          path.replaceWith(stringNodes)
          break
        case METHOD_RENDER_LIST:
          traverseRenderList(path, this)
          path.skip()
          break
        default:
189
          // TODO 检测是否是 filterModules
fxy060608's avatar
fxy060608 已提交
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
          if (!METHOD_BUILT_IN.includes(methodName)) {
            if (
              path.findParent(
                path =>
                  path.isObjectProperty() && ['on', 'nativeOn'].includes(path.node.key.name)
              )
            ) {
              // event
              return path.skip()
            }

            path.replaceWith(
              getMemberExpr(
                path,
                methodName === METHOD_RESOLVE_FILTER
                  ? IDENTIFIER_FILTER
                  : IDENTIFIER_METHOD,
                path.node,
                this
              )
            )
          }
          break
      }
    } else if (
      t.isCallExpression(callee) &&
216 217
      t.isIdentifier(callee.callee) &&
      callee.callee.name === METHOD_RESOLVE_FILTER
fxy060608's avatar
fxy060608 已提交
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 259 260 261 262 263
    ) {
      // multi filter
      path.replaceWith(getMemberExpr(path, IDENTIFIER_FILTER, path.node, this))
    } else if (
      t.isMemberExpression(callee) // message.split('').reverse().join('')
    ) {
      // Object.assign...
      path.replaceWith(getMemberExpr(path, IDENTIFIER_GLOBAL, path.node, this))
    }
  },
  TemplateLiteral (path) {
    const nodes = []
    const expressions = path.get('expressions')

    let index = 0
    for (const elem of path.node.quasis) {
      if (elem.value.cooked) {
        nodes.push(t.stringLiteral(elem.value.cooked))
      }

      if (index < expressions.length) {
        const expr = expressions[index++]
        const node = expr.node
        if (!t.isStringLiteral(node, {
          value: ''
        })) {
          nodes.push(node)
        }
      }
    }

    // since `+` is left-to-right associative
    // ensure the first node is a string if first/second isn't
    const considerSecondNode = !t.isStringLiteral(nodes[1])
    if (!t.isStringLiteral(nodes[0]) && considerSecondNode) {
      nodes.unshift(t.stringLiteral(''))
    }
    let root = nodes[0]

    for (let i = 1; i < nodes.length; i++) {
      root = t.binaryExpression('+', root, nodes[i])
    }

    path.replaceWith(root)
  }
}