visitor.js 8.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8
const t = require('@babel/types')

const {
  METHOD_CREATE_ELEMENT,
  METHOD_TO_STRING,
  METHOD_RENDER_LIST,
  METHOD_BUILT_IN,
  METHOD_RESOLVE_FILTER,
9 10
  METHOD_RENDER_SLOT,
  METHOD_RESOLVE_SCOPED_SLOTS,
fxy060608's avatar
fxy060608 已提交
11 12 13 14 15 16 17 18 19
  IDENTIFIER_FILTER,
  IDENTIFIER_METHOD,
  IDENTIFIER_GLOBAL
} = require('../../constants')

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

20
const {
fxy060608's avatar
fxy060608 已提交
21
  hasOwn,
fxy060608's avatar
fxy060608 已提交
22
  hyphenate,
23
  traverseFilter,
fxy060608's avatar
fxy060608 已提交
24 25 26 27 28 29 30
  getComponentName
} = require('../../util')

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

const getMemberExpr = require('./member-expr')
31 32
const getRenderSlot = require('./render-slot')
const getResolveScopedSlots = require('./resolve-scoped-slots')
fxy060608's avatar
fxy060608 已提交
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

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
  // }
fxy060608's avatar
fxy060608 已提交
63
  if (!hasOwn(state.options, '$vueId')) {
fxy060608's avatar
fxy060608 已提交
64 65
    state.options.$vueId = 1
  }
fxy060608's avatar
fxy060608 已提交
66
  const hashId = state.options.hashId
67
  const vueId = (hashId ? (hashId + '-') : '') + (state.options.$vueId++)
fxy060608's avatar
fxy060608 已提交
68 69 70 71

  let value

  if (state.scoped.length) {
fxy060608's avatar
fxy060608 已提交
72 73
    const scopeds = state.scoped
    const len = scopeds.length
fxy060608's avatar
fxy060608 已提交
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
    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 = {
139
  noScope: false,
140 141 142 143 144 145 146 147
  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 已提交
148 149
  CallExpression (path) {
    const callee = path.node.callee
150 151 152
    if (traverseFilter(callee, this)) {
      return path.skip()
    } else if (t.isIdentifier(callee)) {
fxy060608's avatar
fxy060608 已提交
153 154 155
      const methodName = callee.name
      switch (methodName) {
        case METHOD_CREATE_ELEMENT:
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
          {
            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)
fxy060608's avatar
fxy060608 已提交
184 185 186
          }
          break
        case METHOD_TO_STRING:
187 188 189 190
          {
            const stringNodes = path.node.arguments[0]
            stringNodes.$toString = true
            path.replaceWith(stringNodes)
fxy060608's avatar
fxy060608 已提交
191
          }
fxy060608's avatar
fxy060608 已提交
192 193 194 195 196 197
          break
        case METHOD_RENDER_LIST:
          traverseRenderList(path, this)
          path.skip()
          break
        default:
198
          // TODO 检测是否是 filterModules
fxy060608's avatar
fxy060608 已提交
199 200 201 202 203 204 205 206 207 208
          if (!METHOD_BUILT_IN.includes(methodName)) {
            if (
              path.findParent(
                path =>
                  path.isObjectProperty() && ['on', 'nativeOn'].includes(path.node.key.name)
              )
            ) {
              // event
              return path.skip()
            }
209 210 211 212 213
            path = path.findParent((path) => path.isLogicalExpression()) || path
            path.skip()
            if (path.findParent((path) => path.shouldSkip)) {
              return
            }
fxy060608's avatar
fxy060608 已提交
214 215 216 217 218 219 220 221 222 223
            path.replaceWith(
              getMemberExpr(
                path,
                methodName === METHOD_RESOLVE_FILTER
                  ? IDENTIFIER_FILTER
                  : IDENTIFIER_METHOD,
                path.node,
                this
              )
            )
224 225 226 227 228 229
          } else if (this.options.betterScopedSlots) {
            if (methodName === METHOD_RESOLVE_SCOPED_SLOTS) {
              getResolveScopedSlots(path, this)
            } else if (methodName === METHOD_RENDER_SLOT) {
              getRenderSlot(path, this)
            }
fxy060608's avatar
fxy060608 已提交
230 231 232 233 234
          }
          break
      }
    } else if (
      t.isCallExpression(callee) &&
235 236
      t.isIdentifier(callee.callee) &&
      callee.callee.name === METHOD_RESOLVE_FILTER
fxy060608's avatar
fxy060608 已提交
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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    ) {
      // 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)
  }
282
}