util.js 17.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import Vue from 'vue'

3 4 5
import {
  isFn,
  noop,
6
  hasOwn,
7 8 9
  isPlainObject
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
10 11
export const PAGE_EVENT_HOOKS = [
  'onPullDownRefresh',
12 13
  'onReachBottom',
  'onAddToFavorites',
14
  'onShareTimeline',
fxy060608's avatar
fxy060608 已提交
15 16 17 18 19
  'onShareAppMessage',
  'onPageScroll',
  'onResize',
  'onTabItemTap'
]
20

fxy060608's avatar
fxy060608 已提交
21
export function initMocks (vm, mocks) {
22
  const mpInstance = vm.$mp[vm.mpType]
fxy060608's avatar
fxy060608 已提交
23
  mocks.forEach(mock => {
24 25 26 27 28 29
    if (hasOwn(mpInstance, mock)) {
      vm[mock] = mpInstance[mock]
    }
  })
}

fxy060608's avatar
fxy060608 已提交
30 31 32
function hasHook (hook, vueOptions) {
  if (!vueOptions) {
    return true
fxy060608's avatar
fxy060608 已提交
33 34
  }

fxy060608's avatar
fxy060608 已提交
35 36 37 38
  if (Vue.options && Array.isArray(Vue.options[hook])) {
    return true
  }

fxy060608's avatar
fxy060608 已提交
39 40 41 42 43 44 45
  vueOptions = vueOptions.default || vueOptions

  if (isFn(vueOptions)) {
    if (isFn(vueOptions.extendOptions[hook])) {
      return true
    }
    if (vueOptions.super &&
fxy060608's avatar
fxy060608 已提交
46 47
      vueOptions.super.options &&
      Array.isArray(vueOptions.super.options[hook])) {
fxy060608's avatar
fxy060608 已提交
48 49 50 51
      return true
    }
    return false
  }
fxy060608's avatar
fxy060608 已提交
52 53 54 55 56 57 58 59 60 61 62

  if (isFn(vueOptions[hook])) {
    return true
  }
  const mixins = vueOptions.mixins
  if (Array.isArray(mixins)) {
    return !!mixins.find(mixin => hasHook(hook, mixin))
  }
}

export function initHooks (mpOptions, hooks, vueOptions) {
63
  hooks.forEach(hook => {
fxy060608's avatar
fxy060608 已提交
64
    if (hasHook(hook, vueOptions)) {
fxy060608's avatar
fxy060608 已提交
65 66 67
      mpOptions[hook] = function (args) {
        return this.$vm && this.$vm.__call_hook(hook, args)
      }
68 69
    }
  })
fxy060608's avatar
fxy060608 已提交
70
}
71

DCloud-WZF's avatar
DCloud-WZF 已提交
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
export function initUnknownHooks (mpOptions, vueOptions, excludes = []) {
  findHooks(vueOptions).forEach((hook) => initHook(mpOptions, hook, excludes))
}

function findHooks (vueOptions, hooks = []) {
  if (vueOptions) {
    Object.keys(vueOptions).forEach((name) => {
      if (name.indexOf('on') === 0 && isFn(vueOptions[name])) {
        hooks.push(name)
      }
    })
  }
  return hooks
}

function initHook (mpOptions, hook, excludes) {
  if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) {
    mpOptions[hook] = function (args) {
      if (
        (__PLATFORM__ === 'mp-toutiao' || __PLATFORM__ === 'mp-lark') &&
        hook === 'onError'
      ) {
        return getApp().$vm.$callHook(hook, args)
      }
      return this.$vm && this.$vm.__call_hook(hook, args)
    }
  }
}

fxy060608's avatar
fxy060608 已提交
101 102 103 104 105 106 107 108
export function initVueComponent (Vue, vueOptions) {
  vueOptions = vueOptions.default || vueOptions
  let VueComponent
  if (isFn(vueOptions)) {
    VueComponent = vueOptions
  } else {
    VueComponent = Vue.extend(vueOptions)
  }
D
Danny 已提交
109
  vueOptions = VueComponent.options
fxy060608's avatar
fxy060608 已提交
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
  return [VueComponent, vueOptions]
}

export function initSlots (vm, vueSlots) {
  if (Array.isArray(vueSlots) && vueSlots.length) {
    const $slots = Object.create(null)
    vueSlots.forEach(slotName => {
      $slots[slotName] = true
    })
    vm.$scopedSlots = vm.$slots = $slots
  }
}

export function initVueIds (vueIds, mpInstance) {
  vueIds = (vueIds || '').split(',')
  const len = vueIds.length

  if (len === 1) {
    mpInstance._$vueId = vueIds[0]
  } else if (len === 2) {
    mpInstance._$vueId = vueIds[0]
    mpInstance._$vuePid = vueIds[1]
  }
}

export function initData (vueOptions, context) {
fxy060608's avatar
fxy060608 已提交
136 137
  let data = vueOptions.data || {}
  const methods = vueOptions.methods || {}
138 139 140

  if (typeof data === 'function') {
    try {
fxy060608's avatar
fxy060608 已提交
141
      data = data.call(context) // 支持 Vue.prototype 上挂的数据
142
    } catch (e) {
143 144 145
      if (process.env.VUE_APP_DEBUG) {
        console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data)
      }
146
    }
147 148 149 150 151
  } else {
    try {
      // 对 data 格式化
      data = JSON.parse(JSON.stringify(data))
    } catch (e) {}
152 153 154 155
  }

  if (!isPlainObject(data)) {
    data = {}
156
  }
fxy060608's avatar
fxy060608 已提交
157

158
  Object.keys(methods).forEach(methodName => {
fxy060608's avatar
fxy060608 已提交
159
    if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
160 161 162 163 164
      data[methodName] = methods[methodName]
    }
  })

  return data
165 166 167 168
}

const PROP_TYPES = [String, Number, Boolean, Object, Array, null]

fxy060608's avatar
fxy060608 已提交
169 170 171 172 173 174 175 176
function createObserver (name) {
  return function observer (newVal, oldVal) {
    if (this.$vm) {
      this.$vm[name] = newVal // 为了触发其他非 render watcher
    }
  }
}

fxy060608's avatar
fxy060608 已提交
177
export function initBehaviors (vueOptions, initBehavior) {
fxy060608's avatar
fxy060608 已提交
178 179 180
  const vueBehaviors = vueOptions.behaviors
  const vueExtends = vueOptions.extends
  const vueMixins = vueOptions.mixins
fxy060608's avatar
fxy060608 已提交
181

fxy060608's avatar
fxy060608 已提交
182
  let vueProps = vueOptions.props
fxy060608's avatar
fxy060608 已提交
183 184

  if (!vueProps) {
fxy060608's avatar
fxy060608 已提交
185
    vueOptions.props = vueProps = []
fxy060608's avatar
fxy060608 已提交
186 187
  }

188
  const behaviors = []
fxy060608's avatar
fxy060608 已提交
189 190 191 192 193 194 195 196
  if (Array.isArray(vueBehaviors)) {
    vueBehaviors.forEach(behavior => {
      behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`))
      if (behavior === 'uni://form-field') {
        if (Array.isArray(vueProps)) {
          vueProps.push('name')
          vueProps.push('value')
        } else {
fxy060608's avatar
fxy060608 已提交
197
          vueProps.name = {
198 199 200
            type: String,
            default: ''
          }
fxy060608's avatar
fxy060608 已提交
201
          vueProps.value = {
202 203 204
            type: [String, Number, Boolean, Array, Object, Date],
            default: ''
          }
fxy060608's avatar
fxy060608 已提交
205 206 207 208
        }
      }
    })
  }
209 210 211
  if (__PLATFORM__ === 'mp-alipay') { // alipay 重复定义props会报错,下边的代码对于其他平台也没有意义,保险起见,仅对alipay做处理
    return
  }
212 213
  if (isPlainObject(vueExtends) && vueExtends.props) {
    behaviors.push(
214
      initBehavior({
fxy060608's avatar
fxy060608 已提交
215
        properties: initProperties(vueExtends.props, true)
216 217 218 219 220 221 222
      })
    )
  }
  if (Array.isArray(vueMixins)) {
    vueMixins.forEach(vueMixin => {
      if (isPlainObject(vueMixin) && vueMixin.props) {
        behaviors.push(
223
          initBehavior({
fxy060608's avatar
fxy060608 已提交
224
            properties: initProperties(vueMixin.props, true)
225 226 227 228 229 230 231 232
          })
        )
      }
    })
  }
  return behaviors
}

233
function parsePropType (key, type, defaultValue, file) {
234 235 236 237 238 239
  // [String]=>String
  if (Array.isArray(type) && type.length === 1) {
    return type[0]
  }
  if (__PLATFORM__ === 'mp-baidu') {
    if (
240
      defaultValue === false &&
fxy060608's avatar
fxy060608 已提交
241 242 243 244
      Array.isArray(type) &&
      type.length === 2 &&
      type.indexOf(String) !== -1 &&
      type.indexOf(Boolean) !== -1
245
    ) { // [String,Boolean]=>Boolean
246 247 248 249
      if (file) {
        console.warn(
          `props.${key}.type should use Boolean instead of [String,Boolean] at ${file}`
        )
250
      }
251
      return Boolean
252 253 254 255 256
    }
  }
  return type
}

Q
qiang 已提交
257
export function initProperties (props, isBehavior = false, file = '', options) {
258 259
  const properties = {}
  if (!isBehavior) {
fxy060608's avatar
fxy060608 已提交
260 261 262 263
    properties.vueId = {
      type: String,
      value: ''
    }
Q
qiang 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    if (__PLATFORM__ === 'mp-toutiao' || __PLATFORM__ === 'mp-lark') {
      // 用于字节跳动小程序模拟抽象节点
      properties.generic = {
        type: Object,
        value: null
      }
    }
    if (__PLATFORM__ === 'mp-weixin' || __PLATFORM__ === 'mp-alipay') {
      if (__PLATFORM__ === 'mp-alipay' || options.virtualHost) {
        properties.virtualHostStyle = {
          type: null,
          value: ''
        }
        properties.virtualHostClass = {
          type: null,
          value: ''
        }
      }
282
    }
283 284
    // scopedSlotsCompiler auto
    properties.scopedSlotsCompiler = {
285 286 287
      type: String,
      value: ''
    }
288
    properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
289 290 291 292 293 294 295 296 297 298 299 300 301
      type: null,
      value: [],
      observer: function (newVal, oldVal) {
        const $slots = Object.create(null)
        newVal.forEach(slotName => {
          $slots[slotName] = true
        })
        this.setData({
          $slots
        })
      }
    }
  }
302 303
  if (Array.isArray(props)) { // ['title']
    props.forEach(key => {
fxy060608's avatar
fxy060608 已提交
304 305 306 307
      properties[key] = {
        type: null,
        observer: createObserver(key)
      }
308 309 310 311 312
    })
  } else if (isPlainObject(props)) { // {title:{type:String,default:''},content:String}
    Object.keys(props).forEach(key => {
      const opts = props[key]
      if (isPlainObject(opts)) { // title:{type:String,default:''}
fxy060608's avatar
fxy060608 已提交
313
        let value = opts.default
314 315 316
        if (isFn(value)) {
          value = value()
        }
317

318
        opts.type = parsePropType(key, opts.type, value, file)
319

320
        properties[key] = {
321
          type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null,
fxy060608's avatar
fxy060608 已提交
322 323
          value,
          observer: createObserver(key)
324 325
        }
      } else { // content:String
326
        const type = parsePropType(key, opts, null, file)
fxy060608's avatar
fxy060608 已提交
327
        properties[key] = {
328
          type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
fxy060608's avatar
fxy060608 已提交
329 330
          observer: createObserver(key)
        }
331 332 333 334 335 336 337
      }
    })
  }
  return properties
}

function wrapper (event) {
fxy060608's avatar
fxy060608 已提交
338 339 340 341 342
  // TODO 又得兼容 mpvue 的 mp 对象
  try {
    event.mp = JSON.parse(JSON.stringify(event))
  } catch (e) {}

343 344 345 346
  event.stopPropagation = noop
  event.preventDefault = noop

  event.target = event.target || {}
fxy060608's avatar
fxy060608 已提交
347

348
  if (!hasOwn(event, 'detail')) {
fxy060608's avatar
fxy060608 已提交
349 350
    event.detail = {}
  }
fxy060608's avatar
fxy060608 已提交
351

352 353
  if (hasOwn(event, 'markerId')) {
    event.detail = typeof event.detail === 'object' ? event.detail : {}
354 355 356
    event.detail.markerId = event.markerId
  }

fxy060608's avatar
fxy060608 已提交
357
  if (__PLATFORM__ === 'mp-baidu') { // mp-baidu,checked=>value
fxy060608's avatar
fxy060608 已提交
358 359
    if (
      isPlainObject(event.detail) &&
fxy060608's avatar
fxy060608 已提交
360 361
      hasOwn(event.detail, 'checked') &&
      !hasOwn(event.detail, 'value')
fxy060608's avatar
fxy060608 已提交
362
    ) {
fxy060608's avatar
fxy060608 已提交
363 364 365 366
      event.detail.value = event.detail.checked
    }
  }

fxy060608's avatar
fxy060608 已提交
367 368 369 370
  if (isPlainObject(event.detail)) {
    event.target = Object.assign({}, event.target, event.detail)
  }

371 372 373
  return event
}

fxy060608's avatar
fxy060608 已提交
374 375 376 377 378 379 380 381 382
function getExtraValue (vm, dataPathsArray) {
  let context = vm
  dataPathsArray.forEach(dataPathArray => {
    const dataPath = dataPathArray[0]
    const value = dataPathArray[2]
    if (dataPath || typeof value !== 'undefined') { // ['','',index,'disable']
      const propPath = dataPathArray[1]
      const valuePath = dataPathArray[3]

383 384 385 386 387 388 389 390 391 392 393 394
      let vFor
      if (Number.isInteger(dataPath)) {
        vFor = dataPath
      } else if (!dataPath) {
        vFor = context
      } else if (typeof dataPath === 'string' && dataPath) {
        if (dataPath.indexOf('#s#') === 0) {
          vFor = dataPath.substr(3)
        } else {
          vFor = vm.__get_value(dataPath, context)
        }
      }
fxy060608's avatar
fxy060608 已提交
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

      if (Number.isInteger(vFor)) {
        context = value
      } else if (!propPath) {
        context = vFor[value]
      } else {
        if (Array.isArray(vFor)) {
          context = vFor.find(vForItem => {
            return vm.__get_value(propPath, vForItem) === value
          })
        } else if (isPlainObject(vFor)) {
          context = Object.keys(vFor).find(vForKey => {
            return vm.__get_value(propPath, vFor[vForKey]) === value
          })
        } else {
          console.error('v-for 暂不支持循环数据:', vFor)
        }
      }

      if (valuePath) {
        context = vm.__get_value(valuePath, context)
      }
    }
  })
  return context
}

422
function processEventExtra (vm, extra, event) {
fxy060608's avatar
fxy060608 已提交
423 424 425 426
  const extraObj = {}

  if (Array.isArray(extra) && extra.length) {
    /**
fxy060608's avatar
fxy060608 已提交
427 428 429 430 431 432 433 434 435 436
     *[
     *    ['data.items', 'data.id', item.data.id],
     *    ['metas', 'id', meta.id]
     *],
     *[
     *    ['data.items', 'data.id', item.data.id],
     *    ['metas', 'id', meta.id]
     *],
     *'test'
     */
fxy060608's avatar
fxy060608 已提交
437 438 439 440 441
    extra.forEach((dataPath, index) => {
      if (typeof dataPath === 'string') {
        if (!dataPath) { // model,prop.sync
          extraObj['$' + index] = vm
        } else {
442 443
          if (dataPath === '$event') { // $event
            extraObj['$' + index] = event
444 445 446 447 448 449
          } else if (dataPath === 'arguments') {
            if (event.detail && event.detail.__args__) {
              extraObj['$' + index] = event.detail.__args__
            } else {
              extraObj['$' + index] = [event]
            }
450 451 452 453 454
          } else if (dataPath.indexOf('$event.') === 0) { // $event.target.value
            extraObj['$' + index] = vm.__get_value(dataPath.replace('$event.', ''), event)
          } else {
            extraObj['$' + index] = vm.__get_value(dataPath)
          }
fxy060608's avatar
fxy060608 已提交
455 456 457 458 459 460 461 462 463 464
        }
      } else {
        extraObj['$' + index] = getExtraValue(vm, dataPath)
      }
    })
  }

  return extraObj
}

fxy060608's avatar
fxy060608 已提交
465 466 467 468 469 470 471 472 473
function getObjByArray (arr) {
  const obj = {}
  for (let i = 1; i < arr.length; i++) {
    const element = arr[i]
    obj[element[0]] = element[1]
  }
  return obj
}

fxy060608's avatar
fxy060608 已提交
474
function processEventArgs (vm, event, args = [], extra = [], isCustom, methodName) {
fxy060608's avatar
fxy060608 已提交
475
  let isCustomMPEvent = false // wxcomponent 组件,传递原始 event 对象
476
  if (isCustom) { // 自定义事件
fxy060608's avatar
fxy060608 已提交
477
    isCustomMPEvent = event.currentTarget &&
fxy060608's avatar
fxy060608 已提交
478 479
      event.currentTarget.dataset &&
      event.currentTarget.dataset.comType === 'wx'
fxy060608's avatar
fxy060608 已提交
480 481 482 483
    if (!args.length) { // 无参数,直接传入 event 或 detail 数组
      if (isCustomMPEvent) {
        return [event]
      }
fxy060608's avatar
fxy060608 已提交
484
      return event.detail.__args__ || event.detail
485
    }
486
  }
fxy060608's avatar
fxy060608 已提交
487

488
  const extraObj = processEventExtra(vm, extra, event)
fxy060608's avatar
fxy060608 已提交
489

490 491 492
  const ret = []
  args.forEach(arg => {
    if (arg === '$event') {
fxy060608's avatar
fxy060608 已提交
493 494 495
      if (methodName === '__set_model' && !isCustom) { // input v-model value
        ret.push(event.target.value)
      } else {
fxy060608's avatar
fxy060608 已提交
496
        if (isCustom && !isCustomMPEvent) {
fxy060608's avatar
fxy060608 已提交
497
          ret.push(event.detail.__args__[0])
fxy060608's avatar
fxy060608 已提交
498 499 500
        } else { // wxcomponent 组件或内置组件
          ret.push(event)
        }
fxy060608's avatar
fxy060608 已提交
501
      }
502
    } else {
fxy060608's avatar
fxy060608 已提交
503 504 505
      if (Array.isArray(arg) && arg[0] === 'o') {
        ret.push(getObjByArray(arg))
      } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
fxy060608's avatar
fxy060608 已提交
506 507 508 509
        ret.push(extraObj[arg])
      } else {
        ret.push(arg)
      }
510 511 512 513 514 515 516 517 518
    }
  })

  return ret
}

const ONCE = '~'
const CUSTOM = '^'

fxy060608's avatar
fxy060608 已提交
519 520
function isMatchEventType (eventType, optType) {
  return (eventType === optType) ||
fxy060608's avatar
fxy060608 已提交
521 522 523 524 525 526 527
    (
      optType === 'regionchange' &&
      (
        eventType === 'begin' ||
        eventType === 'end'
      )
    )
fxy060608's avatar
fxy060608 已提交
528 529
}

530 531 532 533 534 535 536 537 538
function getContextVm (vm) {
  let $parent = vm.$parent
  // 父组件是 scoped slots 或者其他自定义组件时继续查找
  while ($parent && $parent.$parent && ($parent.$options.generic || $parent.$parent.$options.generic || $parent.$scope._$vuePid)) {
    $parent = $parent.$parent
  }
  return $parent && $parent.$parent
}

539 540 541
export function handleEvent (event) {
  event = wrapper(event)

fxy060608's avatar
fxy060608 已提交
542 543 544
  // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
  const dataset = (event.currentTarget || event.target).dataset
  if (!dataset) {
fxy060608's avatar
fxy060608 已提交
545
    return console.warn('事件信息不存在')
546
  }
fxy060608's avatar
fxy060608 已提交
547
  const eventOpts = dataset.eventOpts || dataset['event-opts'] // 支付宝 web-view 组件 dataset 非驼峰
548
  if (!eventOpts) {
fxy060608's avatar
fxy060608 已提交
549
    return console.warn('事件信息不存在')
550 551 552 553
  }

  // [['handle',[1,2,a]],['handle1',[1,2,a]]]
  const eventType = event.type
fxy060608's avatar
fxy060608 已提交
554 555 556

  const ret = []

557 558 559 560 561 562 563 564 565
  eventOpts.forEach(eventOpt => {
    let type = eventOpt[0]
    const eventsArray = eventOpt[1]

    const isCustom = type.charAt(0) === CUSTOM
    type = isCustom ? type.slice(1) : type
    const isOnce = type.charAt(0) === ONCE
    type = isOnce ? type.slice(1) : type

fxy060608's avatar
fxy060608 已提交
566
    if (eventsArray && isMatchEventType(eventType, type)) {
567
      eventsArray.forEach(eventArray => {
568
        const methodName = eventArray[0]
fxy060608's avatar
fxy060608 已提交
569
        if (methodName) {
fxy060608's avatar
fxy060608 已提交
570
          let handlerCtx = this.$vm
571 572
          if (handlerCtx.$options.generic) { // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots
            handlerCtx = getContextVm(handlerCtx) || handlerCtx
573 574 575 576 577 578 579 580 581 582 583 584
          }
          if (methodName === '$emit') {
            handlerCtx.$emit.apply(handlerCtx,
              processEventArgs(
                this.$vm,
                event,
                eventArray[1],
                eventArray[2],
                isCustom,
                methodName
              ))
            return
fxy060608's avatar
fxy060608 已提交
585
          }
586
          const handler = handlerCtx[methodName]
fxy060608's avatar
fxy060608 已提交
587
          if (!isFn(handler)) {
D
DCloud_LXH 已提交
588 589 590
            const type = this.$vm.mpType === 'page' ? 'Page' : 'Component'
            const path = this.route || this.is
            throw new Error(`${type} "${path}" does not have a method "${methodName}"`)
fxy060608's avatar
fxy060608 已提交
591 592 593 594 595 596
          }
          if (isOnce) {
            if (handler.once) {
              return
            }
            handler.once = true
597
          }
598
          let params = processEventArgs(
fxy060608's avatar
fxy060608 已提交
599 600 601 602 603 604
            this.$vm,
            event,
            eventArray[1],
            eventArray[2],
            isCustom,
            methodName
605
          )
606
          params = Array.isArray(params) ? params : []
607
          // 参数尾部增加原始事件对象用于复杂表达式内获取额外数据
608 609 610 611 612
          if (/=\s*\S+\.eventParams\s*\|\|\s*\S+\[['"]event-params['"]\]/.test(handler.toString())) {
            // eslint-disable-next-line no-sparse-arrays
            params = params.concat([, , , , , , , , , , event])
          }
          ret.push(handler.apply(handlerCtx, params))
613 614 615 616
        }
      })
    }
  })
fxy060608's avatar
fxy060608 已提交
617

fxy060608's avatar
fxy060608 已提交
618 619 620 621 622
  if (
    eventType === 'input' &&
    ret.length === 1 &&
    typeof ret[0] !== 'undefined'
  ) {
fxy060608's avatar
fxy060608 已提交
623 624
    return ret[0]
  }
625
}