traverse.js 15.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6
const path = require('path')

const t = require('@babel/types')
const babelTraverse = require('@babel/traverse').default

const generate = require('./generate')
d-u-a's avatar
d-u-a 已提交
7
const uniI18n = require('@dcloudio/uni-cli-i18n')
fxy060608's avatar
fxy060608 已提交
8 9 10 11 12

const {
  genCode,
  getCode,
  getForKey,
13 14
  traverseKey,
  isComponent
fxy060608's avatar
fxy060608 已提交
15 16
} = require('../util')

17 18 19 20
const {
  ATTE_DATA_CUSTOM_HIDDEN
} = require('../constants')

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 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
module.exports = function traverse (ast, state = {}) {
  babelTraverse(ast, {
    WithStatement (path) {
      state.ast = traverseExpr(path.node.body.body[0].argument, state)
    }
  })
  initParent(state.ast)
  return state.ast
}

function initParent (ast, parentNode) {
  if (Array.isArray(ast)) {
    ast.forEach(node => initParent(node, parentNode))
  } else if (typeof ast === 'object') {
    ast.parent = parentNode

    const vueId = ast.$vueId
    if (vueId) {
      const vuePid = getVueParentId(parentNode)
      if (vuePid) {
        ast.attr['vue-id'] = genCode(
          t.binaryExpression(
            '+',
            t.binaryExpression(
              '+',
              t.parenthesizedExpression(vueId),
              t.stringLiteral(',')
            ),
            t.parenthesizedExpression(vuePid)
          )
        )
      }
    }
    initParent(ast.children, ast)
  }
}

function getVueParentId (parentNode) {
  if (!parentNode) {
    return
  }
  return parentNode.$vueId || getVueParentId(parentNode.parent)
}

function traverseExpr (exprNode, state) {
  if (t.isCallExpression(exprNode)) {
    return traverseCallExpr(exprNode, state)
  } else if (t.isConditionalExpression(exprNode)) {
    return traverseConditionalExpr(exprNode, state)
  } else if (t.isArrayExpression(exprNode)) {
    return traverseArrayExpression(exprNode, state)
  } else if (t.isIdentifier(exprNode) && exprNode.name === 'undefined') {
    return {
      type: 'block',
      attr: {},
      children: []
    }
  } else if (t.isUnaryExpression(exprNode) && exprNode.operator === 'void') {
    return false
  } else {
    throw new Error(`暂不支持 ${getCode(exprNode)} 语法`)
  }
}

const traverses = {
  _c: traverseCreateElement,
  _t: traverseRenderSlot,
  _l: traverseRenderList,
  _u: traverseResolveScopedSlots,
  _v: traverseCreateTextVNode,
  _e: traverseCreateEmptyVNode,
  _g: '暂不支持 v-on="$listeners" 用法',
  _b: '暂不支持 v-bind="" 用法'
}

function traverseCallExpr (callExprNode, state) {
  const traverse = traverses[callExprNode.callee.name]
  if (!traverse) {
    throw new Error(
      `CallExpression ${callExprNode.callee.name}  is not yet implemented`
    )
  } else if (typeof traverse === 'string') {
    throw new Error(traverse)
  }

  return traverse(callExprNode, state)
}

function traverseConditionalExpr (conditionalExprNode, state) {
fxy060608's avatar
fxy060608 已提交
110
  const prefix = state.options.platform.directive
fxy060608's avatar
fxy060608 已提交
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
  const ret = [{
    type: 'block',
    attr: {
      [prefix + 'if']: genCode(conditionalExprNode.test)
    },
    children: normalizeChildren(
      traverseExpr(conditionalExprNode.consequent, state)
    )
  }]
  if (
    !(
      t.isCallExpression(conditionalExprNode.alternate) &&
      t.isIdentifier(conditionalExprNode.alternate.callee) &&
      conditionalExprNode.alternate.callee.name === '_e'
    )
  ) {
    // test?_c():_e()
    ret.push({
      type: 'block',
      attr: {
        [prefix + 'else']: ''
      },
      children: normalizeChildren(
        traverseExpr(conditionalExprNode.alternate, state)
      )
    })
  }
  return ret
}

function traverseCreateElement (callExprNode, state) {
  const args = callExprNode.arguments
  const tagNode = args[0]
  if (!t.isStringLiteral(tagNode)) {
    throw new Error(`暂不支持动态组件[${tagNode.name}]`)
  }

  const node = {
    type: tagNode.value,
    attr: {},
    children: []
  }

  if (args.length < 2) {
    return node
  }

  const dataNodeOrChildNodes = args[1]
  if (t.isObjectExpression(dataNodeOrChildNodes)) {
    Object.assign(node.attr, traverseDataNode(dataNodeOrChildNodes, state, node))
  } else {
    node.children = normalizeChildren(traverseExpr(dataNodeOrChildNodes, state))
  }
  if (args.length < 3) {
    return node
  }
  const childNodes = args[2]
  if (!t.isNumericLiteral(childNodes)) {
    if (node.children && node.children.length) {
      node.children = node.children.concat(normalizeChildren(traverseExpr(childNodes, state)))
    } else {
      node.children = normalizeChildren(traverseExpr(childNodes, state))
173
    }
fxy060608's avatar
fxy060608 已提交
174 175 176 177 178 179 180 181 182 183 184
  }
  return node
}

function traverseDataNode (dataNode, state, node) {
  const ret = {}
  const specialEvents = state.options.platform.specialEvents[node.type] || {}
  const specialEventNames = Object.keys(specialEvents)
  dataNode.properties.forEach(property => {
    switch (property.key.name) {
      case 'slot':
fxy060608's avatar
fxy060608 已提交
185
        ret.slot = genCode(property.value)
fxy060608's avatar
fxy060608 已提交
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
        break
      case 'scopedSlots': // Vue 2.6
        property.value.$node = node
        node.children = normalizeChildren(traverseExpr(property.value, state))
        break
      case 'attrs':
      case 'domProps':
      case 'on':
      case 'nativeOn':
        property.value.properties.forEach(attrProperty => {
          if (attrProperty.key.value === 'vue-id') { // initParent 时再处理 vue-id
            node.$vueId = attrProperty.value
            ret[attrProperty.key.value] = genCode(attrProperty.value)
          } else {
            if (specialEventNames.includes(attrProperty.key.value)) {
              if (t.isIdentifier(attrProperty.value)) {
                ret[specialEvents[attrProperty.key.value]] = attrProperty.value.name
              }
            } else {
              ret[attrProperty.key.value] = genCode(attrProperty.value)
            }
          }
        })
        break
      case 'class':
      case 'staticClass':
fxy060608's avatar
fxy060608 已提交
212
        ret.class = genCode(property.value)
fxy060608's avatar
fxy060608 已提交
213 214 215
        break
      case 'style':
      case 'staticStyle':
fxy060608's avatar
fxy060608 已提交
216
        ret.style = genCode(property.value)
fxy060608's avatar
fxy060608 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230
        break
      case 'directives':
        property.value.elements.find(objectExpression => {
          if (t.isObjectExpression(objectExpression)) {
            const nameProperty = objectExpression.properties[0]
            const isShowDir =
              nameProperty &&
              nameProperty.key.name === 'name' &&
              t.isStringLiteral(nameProperty.value) &&
              nameProperty.value.value === 'show'
            if (isShowDir) {
              objectExpression.properties.find(valueProperty => {
                const isValue = valueProperty.key.name === 'value'
                if (isValue) {
231
                  let key
232
                  // 自定义组件不支持 hidden 属性
233 234 235 236 237 238 239 240 241
                  const platform = state.options.platform.name
                  const platforms = ['mp-weixin', 'mp-qq', 'mp-toutiao']
                  if (isComponent(node.type) && platforms.includes(platform)) {
                    // 字节跳动小程序自定义属性不会反应在DOM上,只能使用事件格式
                    key = `${platform === 'mp-toutiao' ? 'bind:-' : ''}${ATTE_DATA_CUSTOM_HIDDEN}`
                  } else {
                    key = 'hidden'
                  }
                  ret[key] = genCode(valueProperty.value, false, true)
fxy060608's avatar
fxy060608 已提交
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
                }
                return isValue
              })
            }
            return isShowDir
          }
        })
        break
    }
  })
  return ret
}

function normalizeChildren (nodes) {
  if (!Array.isArray(nodes)) {
    nodes = [nodes]
  }
  return nodes.filter(node => {
    if (typeof node === 'string' && !node.trim()) {
      return false
    }
    return true
  })
}

function traverseArrayExpression (arrayExprNodes, state) {
  return arrayExprNodes.elements.reduce((nodes, exprNode) => {
    return nodes.concat(traverseExpr(exprNode, state))
  }, [])
}

function genSlotNode (slotName, slotNode, fallbackNodes, state) {
  if (!fallbackNodes || t.isNullLiteral(fallbackNodes)) {
    return slotNode
  }
277 278 279 280
  // 支付宝小程序默认插槽为 $default
  if (state.options.platform.name === 'mp-alipay') {
    slotName = slotName === 'default' ? '$default' : slotName
  }
fxy060608's avatar
fxy060608 已提交
281
  const prefix = state.options.platform.directive
fxy060608's avatar
fxy060608 已提交
282 283 284 285 286
  return [{
    type: 'block',
    attr: {
      [prefix + 'if']: '{{$slots.' + slotName + '}}'
    },
287
    children: [].concat(slotNode)
fxy060608's avatar
fxy060608 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300
  }, {
    type: 'block',
    attr: {
      [prefix + 'else']: ''
    },
    children: normalizeChildren(
      traverseExpr(fallbackNodes, state)
    )
  }]
}

function traverseRenderSlot (callExprNode, state) {
  if (!t.isStringLiteral(callExprNode.arguments[0])) {
Q
qiang 已提交
301
    state.errors.add(uniI18n.__('templateCompiler.notSupportDynamicSlotName', { 0: 'v-slot' }))
fxy060608's avatar
fxy060608 已提交
302 303 304 305 306 307
    return
  }

  const slotName = callExprNode.arguments[0].value

  let deleteSlotName = false // 标记是否组件 slot 手动指定了 name="default"
308
  if (state.options.scopedSlotsCompiler !== 'augmented' && callExprNode.arguments.length > 2) { // 作用域插槽
fxy060608's avatar
fxy060608 已提交
309 310 311 312
    const props = {}
    callExprNode.arguments[2].properties.forEach(property => {
      props[property.key.value] = genCode(property.value)
    })
fxy060608's avatar
fxy060608 已提交
313
    deleteSlotName = props.SLOT_DEFAULT && Object.keys(props).length === 1
fxy060608's avatar
fxy060608 已提交
314
    if (!deleteSlotName) {
fxy060608's avatar
fxy060608 已提交
315
      delete props.SLOT_DEFAULT
fxy060608's avatar
fxy060608 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      return genSlotNode(
        slotName,
        state.options.platform.createScopedSlots(slotName, props, state),
        callExprNode.arguments[1],
        state
      )
    }
  }

  const node = {
    type: 'slot',
    attr: {
      name: slotName
    },
    children: []
  }

  if (deleteSlotName) {
    delete node.attr.name
  }

  return genSlotNode(slotName, node, callExprNode.arguments[1], state)
}

function traverseResolveScopedSlots (callExprNode, state) {
341 342 343 344 345 346 347 348 349 350 351 352 353 354
  function single (children, slotName, ignore) {
    if (Array.isArray(children) && children.length === 1) {
      const child = children[0]
      if (!child.type) {
        return
      }
      if (ignore.includes(child.type)) {
        return single(child.children, slotName, ignore)
      }
      child.attr = child.attr || {}
      child.attr.slot = slotName
      return true
    }
  }
fxy060608's avatar
fxy060608 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  return callExprNode.arguments[0].elements.map(slotNode => {
    let keyProperty = false
    let fnProperty = false
    let proxyProperty = false
    slotNode.properties.forEach(property => {
      switch (property.key.name) {
        case 'key':
          keyProperty = property
          break
        case 'fn':
          fnProperty = property
          break
        case 'proxy':
          proxyProperty = property
      }
    })
    const slotName = keyProperty.value.value
    const returnExprNodes = fnProperty.value.body.body[0].argument
373 374
    const parentNode = callExprNode.$node
    if (slotNode.scopedSlotsCompiler !== 'augmented' && !proxyProperty) {
fxy060608's avatar
fxy060608 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
      const resourcePath = state.options.resourcePath
      const ownerName = path.basename(resourcePath, path.extname(resourcePath))

      const parentName = parentNode.type

      const paramExprNode = fnProperty.value.params[0]
      return state.options.platform.resolveScopedSlots(
        slotName, {
          genCode,
          generate,
          ownerName,
          parentName,
          parentNode,
          resourcePath,
          paramExprNode,
          returnExprNodes,
391 392 393 394 395
          traverseExpr: function (exprNode, state) {
            const ast = traverseExpr(exprNode, state)
            initParent(ast)
            return ast
          },
fxy060608's avatar
fxy060608 已提交
396 397 398 399 400
          normalizeChildren
        },
        state
      )
    }
401 402 403
    if (state.options.scopedSlotsCompiler === 'auto' && slotNode.scopedSlotsCompiler === 'augmented') {
      parentNode.attr['scoped-slots-compiler'] = 'augmented'
    }
404 405 406 407 408 409 410
    const children = normalizeChildren(traverseExpr(returnExprNodes, state))
    // 除百度、字节外其他小程序仅默认插槽可以支持多个节点
    if (single(children, slotName, ['template', 'block'])) {
      return children[0]
    }
    return {
      type: 'block',
fxy060608's avatar
fxy060608 已提交
411 412 413
      attr: {
        slot: slotName
      },
414
      children
fxy060608's avatar
fxy060608 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428
    }
  })
}

function traverseRenderList (callExprNode, state) {
  const params = callExprNode.arguments[1].params
  const forItem = params.length > 0 ? params[0].name : 'item'
  const forIndex = params.length > 1 ? params[1].name : ''

  const forReturnStatementArgument =
    callExprNode.arguments[1].body.body[0].argument

  const forKey = traverseKey(forReturnStatementArgument, state)

fxy060608's avatar
fxy060608 已提交
429
  const prefix = state.options.platform.directive
fxy060608's avatar
fxy060608 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

  const attr = {
    [prefix + 'for']: genCode(callExprNode.arguments[0]),
    [prefix + 'for-item']: forItem
  }

  if (forIndex) {
    attr[prefix + 'for-index'] = forIndex
  }

  if (forKey) {
    const key = getForKey(forKey, forIndex, state)
    if (key) {
      attr[prefix + 'key'] = key
    }
  }

447 448
  const children = traverseExpr(forReturnStatementArgument, state)
  // 支付宝小程序在 block 标签上使用 key 时顺序不能保障
449 450
  if (state.options.platform.name === 'mp-alipay' && t.isCallExpression(forReturnStatementArgument) && children &&
    children.type) {
451 452 453 454
    children.attr = children.attr || {}
    Object.assign(children.attr, attr)
    return children
  }
fxy060608's avatar
fxy060608 已提交
455 456 457
  return {
    type: 'block',
    attr,
458
    children: normalizeChildren(children)
fxy060608's avatar
fxy060608 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  }
}

function getLeftStringLiteral (expr) {
  if (t.isBinaryExpression(expr) && !expr.$toString) {
    return getLeftStringLiteral(expr.left)
  } else if (t.isStringLiteral(expr)) {
    return expr
  }
}

function trim (text, type) {
  // TODO 保留换行符?
  if (type === 'left') {
    text = text.trimLeft()
  } else if (type === 'right') {
    text = text.trimRight()
  } else {
    text = text.trim()
  }
  return text
}

function traverseCreateTextVNode (callExprNode, state) {
  // trimStart|Left and trimEnd|End
  const arg = callExprNode.arguments[0]
  if (t.isStringLiteral(arg)) {
    arg.value = trim(arg.value)
  } else if (t.isBinaryExpression(arg) && !arg.$toString) { // 非_s()
    // right
    const right = arg.right
    if (t.isStringLiteral(right)) {
      right.value = trim(right.value, 'right')
    }
    // left
    const left = getLeftStringLiteral(arg.left)
    if (left && left.value) {
      left.value = trim(left.value, 'left')
    }
  }
  if (
    state.options.platform.name === 'mp-baidu' ||
    state.options.platform.name === 'mp-qq'
  ) {
    const code = genCode(arg, false, false, false)
    if (code.indexOf('{{') === 0) {
      if (state.options.platform.name === 'mp-qq') { // 似乎百度也可以走该逻辑, 为了稳定性,仅限 qq
        return code.replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t')
      }
      return code.replace(/([^\\])\\n/g, '$1\\\\n').replace(/([^\\])\\t/g, '$1\\\\t')
    }
    return code
  }
  return genCode(arg, false, false, false).replace(/\\\\n/g, '\\n')
}

function traverseCreateEmptyVNode (callExprNode, state) {
  return ''
517
}