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

const {
  IDENTIFIER_EVENT,
  VUE_EVENT_MODIFIERS,
  INTERNAL_EVENT_PROXY,
  ATTR_DATA_EVENT_OPTS,
9
  ATTR_DATA_EVENT_PARAMS,
fxy060608's avatar
fxy060608 已提交
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
  INTERNAL_SET_SYNC
} = require('../../../constants')

const {
  getCode,
  customize,
  processMemberExpression
} = require('../../../util')

const {
  getEventExpressionStatement
} = require('../statements')

const defaultArgs = t.arrayExpression([t.stringLiteral('$event')])

function addEventExpressionStatement (funcPath, state, isCustom) {
  const identifier = t.identifier(IDENTIFIER_EVENT)
  const stringLiteral = t.stringLiteral(IDENTIFIER_EVENT)
  state.identifierArray.push([identifier, stringLiteral])
  state.initExpressionStatementArray.push(getEventExpressionStatement(identifier, funcPath.node))

  const arrayExpression = [
    stringLiteral
  ]

  const args = []
  if (!isCustom) { // native events
    args.push(t.stringLiteral('$event'))
    arrayExpression.push(t.arrayExpression(args))
  } else { // custom events

  }
  //   if (state.scoped) { // add forItem,forIndex
  //     const scopedArgs = []
  //     state.scoped.forEach(scoped => {
  //       if (scoped.forIndex && scoped.forIndex !== scoped.forItem) {
  //         scopedArgs.push(t.identifier(scoped.forIndex))
  //       }
  //       scopedArgs.push(t.identifier(scoped.forItem))
  //     })
  //     scopedArgs.reverse().forEach(arg => {
  //       args.push(arg)
  //     })
  //   }
  return t.arrayExpression(arrayExpression)
}

function getIdentifierName (element) {
  if (t.isMemberExpression(element)) {
    return getIdentifierName(element.object)
  }
  return element.name.split('.')[0]
}

function getScoped (scopedArray, element, methodName, state) {
  const identifierName = getIdentifierName(element)
  const scoped = scopedArray.find(scoped => {
    if (scoped.forItem === identifierName) {
      return true
    }
  })
  if (scoped) {
    const forExtra = t.cloneDeep(t.arrayExpression(scoped.forExtra))
    if (t.isMemberExpression(element)) {
      // 简单处理
      // item['order']=>item.order
      element = processMemberExpression(element, state)
      // v-for="item in data.items" :key="item.data.id"
      // v-for="meta in item.metas" :key="meta.id" @tap="change(meta,meta.b,true)"
      // ['data.items','data.id',item.data.id]
      // ['metas','id',meta.id]=>['metas','id',meta.id,'b']
      forExtra.elements[forExtra.elements.length - 1].elements.push(
        t.stringLiteral(
          getExtraDataPath(
            getCode(element).replace(scoped.forItem + '.', ''), methodName
          )
        )
      )
    }
    return forExtra
  }
}

function isForIndex (scopedArray, element) {
  if (t.isIdentifier(element)) {
    return scopedArray.find(scoped => {
      if (scoped.forIndex === element.name) {
        return true
      }
    })
  }
  return false
}

function getExtraDataPath (dataPath, methodName) {
  if (methodName === INTERNAL_SET_SYNC) {
    const dataPaths = dataPath.split('.')
    dataPaths.pop()
    return dataPaths.join('.')
  }
  return dataPath
}

function parseMethod (method, state) {
  const elements = method.elements
  const methodName = elements[0].value
  const argsArrayExpr = elements[1]
  if (argsArrayExpr) {
    const extraArrayElements = []
    argsArrayExpr.elements = argsArrayExpr.elements.map((element) => {
      if (t.isIdentifier(element) || t.isMemberExpression(element)) { // item or item.b
        if (state.scoped.length) {
          const forExtra = getScoped(state.scoped, element, methodName, state)
          if (!forExtra) {
            if (isForIndex(state.scoped, element)) {
              return element
            } else {
              extraArrayElements.push(t.stringLiteral(
                getExtraDataPath(getCode(processMemberExpression(element, state)),
                  methodName)
              ))
            }
          } else {
            extraArrayElements.push(forExtra)
          }
        } else {
          extraArrayElements.push(t.stringLiteral(
            getExtraDataPath(getCode(processMemberExpression(element, state)), methodName)
          ))
        }
        return t.stringLiteral('$' + (extraArrayElements.length - 1))
      } else if ( // +1=>1
        t.isUnaryExpression(element) &&
143 144
        element.operator === '+' &&
        t.isNumericLiteral(element.argument)
fxy060608's avatar
fxy060608 已提交
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
      ) {
        element = t.numericLiteral(element.argument.value)
      } else if (t.isObjectExpression(element)) {
        // {name:'a',b:'c',d:123}=>[['name','a'],['b','c'],['d',123]]
        const objectExprElements = [
          t.stringLiteral('o')
        ]
        element.properties.forEach(property => {
          objectExprElements.push(t.arrayExpression([
            t.stringLiteral(property.key.name || property.key.value),
            t.cloneDeep(property.value)
          ]))
        })
        element = t.arrayExpression(objectExprElements)
      }
      return element
    })
    if (extraArrayElements.length) {
      elements.push(t.arrayExpression(extraArrayElements))
    }
  }
}

function getMethodName (methodName) {
  return methodName === '__HOLDER__' ? '' : methodName
}

172
function parseEventByCallExpression (callExpr, methods) {
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
  let methodName = callExpr.callee.name
  if (methodName === '$set') {
    methodName = INTERNAL_SET_SYNC
  }
  const arrayExpression = [t.stringLiteral(getMethodName(methodName))]
  const args = callExpr.arguments
  if (methodName === INTERNAL_SET_SYNC) {
    // v-bind:title.sync="doc.title"
    // ['$set',['doc.a','title','$event']]
    const argsExpression = []
    argsExpression.push(
      t.memberExpression(args[0], t.identifier(args[1].value))
    )
    argsExpression.push(t.stringLiteral(args[1].value))
    argsExpression.push(t.stringLiteral('$event'))
    arrayExpression.push(t.arrayExpression(argsExpression))
  } else {
    if (args.length) {
      const argsExpression = []
      args.forEach(arg => {
        if (t.isIdentifier(arg) && arg.name === '$event') {
          argsExpression.push(t.stringLiteral('$event'))
        } else {
          argsExpression.push(arg)
        }
      })
      arrayExpression.push(t.arrayExpression(argsExpression))
    }
  }
202
  methods.push(t.arrayExpression(arrayExpression))
203 204
}

205 206 207 208
function isValuePath (path) {
  return path.key !== 'key' && path.key !== 'id' && (path.key !== 'property' || path.parent.computed) && !(path.key === 'value' && path.parentPath.parentPath.isObjectPattern()) && !(path.key === 'left' && path.parentPath.parentPath.parentPath.isObjectPattern())
}

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
/**
 * 判断 v-for 中是否包含复杂表达式:数组、对象、方法
 */
const isSafeScoped = (state) => {
  const scopedArray = state.scoped
  for (let index = 0; index < scopedArray.length; index++) {
    const scoped = scopedArray[index]
    const arrayExtra = scoped.forExtra[0].elements[0].value
    // 简易判断
    if (typeof arrayExtra === 'string' && (arrayExtra.startsWith('[') || arrayExtra.startsWith('{') || /\(.*\)/.test(arrayExtra))) {
      return false
    }
  }
  return true
}

fxy060608's avatar
fxy060608 已提交
225 226
function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, tagName, ret) {
  const key = keyPath.node
227
  let type = key.value || key.name || ''
fxy060608's avatar
fxy060608 已提交
228 229 230 231 232 233 234 235

  const isCustom = isComponent && !isNativeOn

  let isCatch = false
  let isCapture = false
  let isPassive = false
  let isOnce = false

fxy060608's avatar
fxy060608 已提交
236
  const methods = []
237
  const params = []
fxy060608's avatar
fxy060608 已提交
238

239
  if (type) {
240 241
    isPassive = type.charAt(0) === VUE_EVENT_MODIFIERS.passive
    type = isPassive ? type.slice(1) : type
fxy060608's avatar
fxy060608 已提交
242

243 244
    isOnce = type.charAt(0) === VUE_EVENT_MODIFIERS.once // Prefixed last, checked first
    type = isOnce ? type.slice(1) : type
fxy060608's avatar
fxy060608 已提交
245

246 247
    isCapture = type.charAt(0) === VUE_EVENT_MODIFIERS.capture
    type = isCapture ? type.slice(1) : type
fxy060608's avatar
fxy060608 已提交
248

249 250
    const specialEvents = state.options.platform.specialEvents
    const isSpecialEvent = specialEvents[tagName] && Object.keys(specialEvents[tagName]).includes(type)
fxy060608's avatar
fxy060608 已提交
251

252 253 254 255 256
    if (!valuePath.isArrayExpression()) {
      valuePath = [valuePath]
    } else {
      valuePath = valuePath.get('elements')
    }
fxy060608's avatar
fxy060608 已提交
257

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    valuePath.forEach(funcPath => {
      if ( // wxs event
        funcPath.isMemberExpression() &&
        t.isIdentifier(funcPath.node.object) &&
        state.options.filterModules.includes(funcPath.node.object.name)
      ) {
        const {
          getEventType,
          formatEventType
        } = state.options.platform
        const wxsEventType = formatEventType(getEventType(type))
        if (key.value) {
          key.value = wxsEventType
        } else {
          key.name = wxsEventType
fxy060608's avatar
fxy060608 已提交
273
        }
274 275 276 277 278 279 280 281 282 283 284 285
      } else if (funcPath.isIdentifier()) { // on:{click:handle}
        if (!isSpecialEvent) {
          const arrayExpression = [t.stringLiteral(getMethodName(funcPath.node.name))]
          if (!isCustom) { // native events
            arrayExpression.push(defaultArgs)
          }
          methods.push(t.arrayExpression(arrayExpression))
        } else {
          if (!state.options.specialMethods) {
            state.options.specialMethods = new Set()
          }
          state.options.specialMethods.add(funcPath.node.name)
fxy060608's avatar
fxy060608 已提交
286
        }
287 288 289 290 291 292
      } else if (isSpecialEvent) {
        state.errors.add(
          `${tagName} 组件 ${type} 事件仅支持 @${type}="methodName" 方式绑定`
        )
      } else {
        let anonymous = true
293

294
        // "click":function($event) {click1(item);click2(item);}
fxy060608's avatar
fxy060608 已提交
295
        const body = funcPath.node.body && funcPath.node.body.body
296 297
        const funcParams = funcPath.node.params
        if (body && body.length && funcParams && funcParams.length === 1) {
298 299
          const exprStatements = body.filter(node => {
            return t.isExpressionStatement(node) && t.isCallExpression(node.expression)
300
          })
301
          if (exprStatements.length === body.length) {
302 303 304 305 306 307 308 309 310 311 312 313 314 315
            const paramPath = funcPath.get('params')[0]
            const paramName = paramPath.node.name
            if (paramName !== '$event') {
              funcPath.get('body').traverse({
                Identifier (path) {
                  const node = path.node
                  const binding = path.scope.getBinding(node.name)
                  if (binding && binding.identifier === paramPath.node && isValuePath(path)) {
                    path.replaceWith(t.identifier('$event'))
                  }
                }
              })
              paramPath.replaceWith(t.identifier('$event'))
            }
fxy060608's avatar
fxy060608 已提交
316
            anonymous = false
317 318 319
            exprStatements.forEach(exprStatement => {
              parseEventByCallExpression(exprStatement.expression, methods)
            })
fxy060608's avatar
fxy060608 已提交
320
          }
321 322
        }

323 324 325
        // 如果 v-for 遍历的值为 数组、对象、方法 则进入底部匿名表达式处理
        if (anonymous && isSafeScoped(state)) {
          funcPath.traverse({
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            noScope: true,
            MemberExpression (path) {
              if (path.node.object.name === '$event' && path.node.property.name ===
                'stopPropagation') {
                isCatch = true
                path.stop()
              }
            },
            AssignmentExpression (path) { // "update:title": function($event) {title = $event}
              const left = path.node.left
              const right = path.node.right
              // v-bind:title.sync="title"
              if (t.isIdentifier(left) &&
                t.isIdentifier(right) &&
                right.name === '$event' &&
                type.indexOf('update:') === 0) {
                methods.push(t.arrayExpression( // ['$set',['title','$event']]
                  [
                    t.stringLiteral(INTERNAL_SET_SYNC),
                    t.arrayExpression([
                      t.identifier(left.name),
                      t.stringLiteral(left.name),
                      t.stringLiteral('$event')
                    ])
                  ]
                ))
352
                anonymous = false
353 354 355 356 357 358 359 360 361 362
                path.stop()
              }
            },
            ReturnStatement (path) {
              const argument = path.node.argument
              if (t.isCallExpression(argument)) {
                if (t.isIdentifier(argument.callee)) { // || t.isMemberExpression(argument.callee)
                  anonymous = false
                  parseEventByCallExpression(argument, methods)
                }
363
              }
fxy060608's avatar
fxy060608 已提交
364
            }
365 366 367
          })
        }

368
        if (anonymous) {
369 370 371 372 373 374
          // 处理复杂表达式中使用的局部变量(主要在v-for中定义)
          funcPath.traverse({
            Identifier (path) {
              const scope = path.scope
              const node = path.node
              const name = node.name
375
              if (isValuePath(path) && scope && !scope.hasOwnBinding(name) && scope.hasBinding(name) && !params.includes(name) && name !== 'undefined') {
376 377 378 379 380 381 382 383
                params.push(name)
              }
            }
          })
          params.forEach(name => {
            funcPath.node.params.push(t.identifier(name))
          })
          if (params.length) {
384 385 386 387 388
            let argumentsName = 'arguments'
            if (funcPath.isArrowFunctionExpression()) {
              argumentsName = 'args'
              funcPath.node.params.push(t.restElement(t.identifier(argumentsName)))
            }
389 390 391
            const datasetUid = funcPath.scope.generateDeclaredUidIdentifier().name
            const paramsUid = funcPath.scope.generateDeclaredUidIdentifier().name
            const dataset = ATTR_DATA_EVENT_PARAMS.substring(5)
392
            const code = `var ${datasetUid}=${argumentsName}[${argumentsName}.length-1].currentTarget.dataset,${paramsUid}=${datasetUid}.${dataset.replace(/-([a-z])/, (_, str) => str.toUpperCase())}||${datasetUid}['${dataset}'],${params.map(item => `${item}=${paramsUid}.${item}`).join(',')}`
393 394
            funcPath.node.body.body.unshift(parser.parse(code).program.body[0])
          }
395
          methods.push(addEventExpressionStatement(funcPath, state, isComponent, isNativeOn))
fxy060608's avatar
fxy060608 已提交
396 397
        }
      }
398 399
    })
  }
fxy060608's avatar
fxy060608 已提交
400 401 402

  return {
    type,
403
    params,
fxy060608's avatar
fxy060608 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416
    methods,
    modifiers: {
      isCatch,
      isCapture,
      isPassive,
      isOnce,
      isCustom
    }
  }
}

function _processEvent (path, state, isComponent, isNativeOn = false, tagName, ret) {
  const opts = []
417 418 419 420
  // remove invalid event
  path.node.value.properties = path.node.value.properties.filter(property => {
    return property.key.value || property.key.name
  })
fxy060608's avatar
fxy060608 已提交
421 422 423 424 425 426 427
  const len = path.node.value.properties.length
  for (let i = 0; i < len; i++) {
    const propertyPath = path.get(`value.properties.${i}`)
    const keyPath = propertyPath.get('key')
    const valuePath = propertyPath.get('value')
    const {
      type,
428
      params,
fxy060608's avatar
fxy060608 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
      methods,
      modifiers: {
        isCatch,
        isCapture,
        isOnce,
        isCustom
      }
    } = parseEvent(
      keyPath,
      valuePath,
      state,
      isComponent,
      isNativeOn,
      tagName,
      ret
    )

    if (!methods.length) {
      continue
    }

    methods.forEach(method => {
      parseMethod(method, state) // 解析参数
    })

    const getEventType = state.options.platform.getEventType

    let optType = isCustom ? customize(type) : getEventType(type) // 比如自定义组件使用了 click 自定义事件

    if (isOnce) {
      optType = VUE_EVENT_MODIFIERS.once + optType
    }
    if (isCustom) {
      optType = VUE_EVENT_MODIFIERS.custom + optType
    }
464 465
    opts.push({
      opt: t.arrayExpression([
fxy060608's avatar
fxy060608 已提交
466 467
        t.stringLiteral(optType),
        t.arrayExpression(methods)
468 469 470
      ]),
      params
    })
fxy060608's avatar
fxy060608 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    keyPath.replaceWith(
      t.stringLiteral(
        state.options.platform.formatEventType(
          isCustom ? customize(type) : getEventType(type), // 比如自定义组件使用了 click 自定义事件
          isCatch,
          isCapture,
          isCustom
        )
      )
    )

    valuePath.replaceWith(t.stringLiteral(INTERNAL_EVENT_PROXY))
  }
  return opts
}
module.exports = function processEvent (paths, path, state, isComponent, tagName) {
fxy060608's avatar
fxy060608 已提交
488 489
  const onPath = paths.on
  const nativeOnPath = paths.nativeOn
fxy060608's avatar
fxy060608 已提交
490 491 492 493

  const ret = []

  const opts = []
494
  const params = []
fxy060608's avatar
fxy060608 已提交
495 496

  if (onPath) {
497
    _processEvent(onPath, state, isComponent, false, tagName, ret).forEach(({ opt, params: array }) => {
fxy060608's avatar
fxy060608 已提交
498
      opts.push(opt)
499
      params.push(...array)
fxy060608's avatar
fxy060608 已提交
500 501 502
    })
  }
  if (nativeOnPath) {
503
    _processEvent(nativeOnPath, state, isComponent, true, tagName, ret).forEach(({ opt, params: array }) => {
fxy060608's avatar
fxy060608 已提交
504
      opts.push(opt)
505
      params.push(...array)
fxy060608's avatar
fxy060608 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518
    })
  }
  if (!opts.length) {
    return ret
  }

  ret.push(
    t.objectProperty(
      t.stringLiteral(ATTR_DATA_EVENT_OPTS),
      t.arrayExpression(opts)
    )
  )

519 520 521 522
  if (params.length) {
    ret.push(
      t.objectProperty(
        t.stringLiteral(ATTR_DATA_EVENT_PARAMS),
Q
qiang 已提交
523 524
        // 直接使用对象格式微信小程序编译会报错
        t.stringLiteral(`{{({${params.join(',')}})}}`)
525 526 527 528
      )
    )
  }

fxy060608's avatar
fxy060608 已提交
529
  return ret
530
}