event.js 12.4 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 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 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 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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 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 317 318 319 320 321 322 323 324 325 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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
const t = require('@babel/types')

const {
  IDENTIFIER_EVENT,
  VUE_EVENT_MODIFIERS,
  INTERNAL_EVENT_PROXY,
  ATTR_DATA_EVENT_OPTS,
  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) &&
                element.operator === '+' &&
                t.isNumericLiteral(element.argument)
      ) {
        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
}

function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, tagName, ret) {
  const key = keyPath.node
  let type = key.value || key.name

  const isCustom = isComponent && !isNativeOn

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

  isPassive = type.charAt(0) === VUE_EVENT_MODIFIERS.passive
  type = isPassive ? type.slice(1) : type

  isOnce = type.charAt(0) === VUE_EVENT_MODIFIERS.once // Prefixed last, checked first
  type = isOnce ? type.slice(1) : type

  isCapture = type.charAt(0) === VUE_EVENT_MODIFIERS.capture
  type = isCapture ? type.slice(1) : type

  const specialEvents = state.options.platform.specialEvents
  const isSpecialEvent = specialEvents[tagName] && Object.keys(specialEvents[tagName]).includes(type)

  let methods = []

  if (!valuePath.isArrayExpression()) {
    valuePath = [valuePath]
  } else {
    valuePath = valuePath.get('elements')
  }

  valuePath.forEach(funcPath => {
    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)
      }
    } 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
      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')
                ])
              ]
            ))
            anonymous = false
            path.stop()
          }
        },
        ReturnStatement (path) {
          const argument = path.node.argument
          if (t.isCallExpression(argument)) {
            if (t.isIdentifier(argument.callee)) {
              anonymous = false
              let methodName = argument.callee.name
              if (methodName === '$set') {
                methodName = INTERNAL_SET_SYNC
              }
              const arrayExpression = [t.stringLiteral(getMethodName(methodName))]
              const args = argument.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))
                }
              }
              methods.push(t.arrayExpression(arrayExpression))
            }
          }
        }
      })
      if (anonymous) {
        methods.push(addEventExpressionStatement(funcPath, state, isComponent, isNativeOn))
      }
    }
  })

  return {
    type,
    methods,
    modifiers: {
      isCatch,
      isCapture,
      isPassive,
      isOnce,
      isCustom
    }
  }
}

function _processEvent (path, state, isComponent, isNativeOn = false, tagName, ret) {
  const opts = []
  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,
      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
    }
    opts.push(
      t.arrayExpression([
        t.stringLiteral(optType),
        t.arrayExpression(methods)
      ])
    )

    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) {
  const onPath = paths['on']
  const nativeOnPath = paths['nativeOn']

  const ret = []

  const opts = []

  if (onPath) {
    _processEvent(onPath, state, isComponent, false, tagName, ret).forEach(opt => {
      opts.push(opt)
    })
  }
  if (nativeOnPath) {
    _processEvent(nativeOnPath, state, isComponent, true, tagName, ret).forEach(opt => {
      opts.push(opt)
    })
  }
  if (!opts.length) {
    return ret
  }

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

  return ret
}