event.js 15.3 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
}

fxy060608's avatar
fxy060608 已提交
205 206
function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, tagName, ret) {
  const key = keyPath.node
207
  let type = key.value || key.name || ''
fxy060608's avatar
fxy060608 已提交
208 209 210 211 212 213 214 215

  const isCustom = isComponent && !isNativeOn

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

fxy060608's avatar
fxy060608 已提交
216
  const methods = []
217
  const params = []
fxy060608's avatar
fxy060608 已提交
218

219
  if (type) {
220 221
    isPassive = type.charAt(0) === VUE_EVENT_MODIFIERS.passive
    type = isPassive ? type.slice(1) : type
fxy060608's avatar
fxy060608 已提交
222

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

226 227
    isCapture = type.charAt(0) === VUE_EVENT_MODIFIERS.capture
    type = isCapture ? type.slice(1) : type
fxy060608's avatar
fxy060608 已提交
228

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

232 233 234 235 236
    if (!valuePath.isArrayExpression()) {
      valuePath = [valuePath]
    } else {
      valuePath = valuePath.get('elements')
    }
fxy060608's avatar
fxy060608 已提交
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    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 已提交
253
        }
254 255 256 257 258 259 260 261 262 263 264 265
      } 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 已提交
266
        }
267 268 269 270 271 272 273 274
      } else if (isSpecialEvent) {
        state.errors.add(
          `${tagName} 组件 ${type} 事件仅支持 @${type}="methodName" 方式绑定`
        )
      } else if (funcPath.isArrowFunctionExpression()) { // e=>count++
        methods.push(addEventExpressionStatement(funcPath, state, isCustom))
      } else {
        let anonymous = true
275

276
        // "click":function($event) {click1(item);click2(item);}
fxy060608's avatar
fxy060608 已提交
277 278
        const body = funcPath.node.body && funcPath.node.body.body
        if (body && body.length) {
279 280
          const exprStatements = body.filter(node => {
            return t.isExpressionStatement(node) && t.isCallExpression(node.expression)
281
          })
282
          if (exprStatements.length === body.length) {
fxy060608's avatar
fxy060608 已提交
283
            anonymous = false
284 285 286
            exprStatements.forEach(exprStatement => {
              parseEventByCallExpression(exprStatement.expression, methods)
            })
fxy060608's avatar
fxy060608 已提交
287
          }
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        }

        anonymous && funcPath.traverse({
          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')
                  ])
                ]
              ))
fxy060608's avatar
fxy060608 已提交
317
              anonymous = false
318 319 320 321 322 323
              path.stop()
            }
          },
          ReturnStatement (path) {
            const argument = path.node.argument
            if (t.isCallExpression(argument)) {
324
              if (t.isIdentifier(argument.callee)) { // || t.isMemberExpression(argument.callee)
325 326 327
                anonymous = false
                parseEventByCallExpression(argument, methods)
              }
fxy060608's avatar
fxy060608 已提交
328 329
            }
          }
330 331
        })
        if (anonymous) {
332 333 334 335 336 337
          // 处理复杂表达式中使用的局部变量(主要在v-for中定义)
          funcPath.traverse({
            Identifier (path) {
              const scope = path.scope
              const node = path.node
              const name = node.name
Q
qiang 已提交
338
              if (path.key !== 'key' && (path.key !== 'property' || path.parent.computed) && scope && !scope.hasOwnBinding(name) && scope.hasBinding(name)) {
339 340 341 342 343 344 345 346 347 348 349 350 351 352
                params.push(name)
              }
            }
          })
          params.forEach(name => {
            funcPath.node.params.push(t.identifier(name))
          })
          if (params.length) {
            const datasetUid = funcPath.scope.generateDeclaredUidIdentifier().name
            const paramsUid = funcPath.scope.generateDeclaredUidIdentifier().name
            const dataset = ATTR_DATA_EVENT_PARAMS.substring(5)
            const code = `var ${datasetUid}=arguments[arguments.length-1].currentTarget.dataset,${paramsUid}=(${datasetUid}.${dataset.replace(/-([a-z])/, (_, str) => str.toUpperCase())}||${datasetUid}['${dataset}'])[0],${params.map(item => `${item}=${paramsUid}.${item}`).join(',')}`
            funcPath.node.body.body.unshift(parser.parse(code).program.body[0])
          }
353
          methods.push(addEventExpressionStatement(funcPath, state, isComponent, isNativeOn))
fxy060608's avatar
fxy060608 已提交
354 355
        }
      }
356 357
    })
  }
fxy060608's avatar
fxy060608 已提交
358 359 360

  return {
    type,
361
    params,
fxy060608's avatar
fxy060608 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374
    methods,
    modifiers: {
      isCatch,
      isCapture,
      isPassive,
      isOnce,
      isCustom
    }
  }
}

function _processEvent (path, state, isComponent, isNativeOn = false, tagName, ret) {
  const opts = []
375 376 377 378
  // remove invalid event
  path.node.value.properties = path.node.value.properties.filter(property => {
    return property.key.value || property.key.name
  })
fxy060608's avatar
fxy060608 已提交
379 380 381 382 383 384 385
  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,
386
      params,
fxy060608's avatar
fxy060608 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
      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
    }
422 423
    opts.push({
      opt: t.arrayExpression([
fxy060608's avatar
fxy060608 已提交
424 425
        t.stringLiteral(optType),
        t.arrayExpression(methods)
426 427 428
      ]),
      params
    })
fxy060608's avatar
fxy060608 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

    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 已提交
446 447
  const onPath = paths.on
  const nativeOnPath = paths.nativeOn
fxy060608's avatar
fxy060608 已提交
448 449 450 451

  const ret = []

  const opts = []
452
  const params = []
fxy060608's avatar
fxy060608 已提交
453 454

  if (onPath) {
455
    _processEvent(onPath, state, isComponent, false, tagName, ret).forEach(({ opt, params: array }) => {
fxy060608's avatar
fxy060608 已提交
456
      opts.push(opt)
457
      params.push(...array)
fxy060608's avatar
fxy060608 已提交
458 459 460
    })
  }
  if (nativeOnPath) {
461
    _processEvent(nativeOnPath, state, isComponent, true, tagName, ret).forEach(({ opt, params: array }) => {
fxy060608's avatar
fxy060608 已提交
462
      opts.push(opt)
463
      params.push(...array)
fxy060608's avatar
fxy060608 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476
    })
  }
  if (!opts.length) {
    return ret
  }

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

477 478 479 480 481 482 483 484 485 486
  if (params.length) {
    ret.push(
      t.objectProperty(
        t.stringLiteral(ATTR_DATA_EVENT_PARAMS),
        // 使用数组格式,直接使用对象格式微信小程序编译会报错
        t.stringLiteral(`{{[{${params.join(',')}}]}}`)
      )
    )
  }

fxy060608's avatar
fxy060608 已提交
487
  return ret
488
}