util.js 12.8 KB
Newer Older
1 2 3
import {
  isFn,
  noop,
4
  hasOwn,
5 6 7
  isPlainObject
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
8 9 10 11 12 13 14 15
export const PAGE_EVENT_HOOKS = [
  'onPullDownRefresh',
  'onReachBottom',
  'onShareAppMessage',
  'onPageScroll',
  'onResize',
  'onTabItemTap'
]
16

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

fxy060608's avatar
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
function hasHook (hook, vueOptions) {
  if (!vueOptions) {
    return true
  }

  vueOptions = vueOptions.default || vueOptions

  if (isFn(vueOptions)) {
    vueOptions = vueOptions.extendOptions
  }

  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) {
47
  hooks.forEach(hook => {
fxy060608's avatar
fxy060608 已提交
48 49 50 51
    if (hasHook(hook, vueOptions)) {
      mpOptions[hook] = function (args) {
        return this.$vm && this.$vm.__call_hook(hook, args)
      }
52 53
    }
  })
fxy060608's avatar
fxy060608 已提交
54
}
55

fxy060608's avatar
fxy060608 已提交
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
export function initVueComponent (Vue, vueOptions) {
  vueOptions = vueOptions.default || vueOptions
  let VueComponent
  if (isFn(vueOptions)) {
    VueComponent = vueOptions
    vueOptions = VueComponent.extendOptions
  } else {
    VueComponent = Vue.extend(vueOptions)
  }
  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 已提交
91 92
  let data = vueOptions.data || {}
  const methods = vueOptions.methods || {}
93 94 95

  if (typeof data === 'function') {
    try {
fxy060608's avatar
fxy060608 已提交
96
      data = data.call(context) // 支持 Vue.prototype 上挂的数据
97
    } catch (e) {
98 99 100
      if (process.env.VUE_APP_DEBUG) {
        console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data)
      }
101
    }
102 103 104 105 106
  } else {
    try {
      // 对 data 格式化
      data = JSON.parse(JSON.stringify(data))
    } catch (e) {}
107 108 109 110
  }

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

113
  Object.keys(methods).forEach(methodName => {
fxy060608's avatar
fxy060608 已提交
114
    if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
115 116 117 118 119
      data[methodName] = methods[methodName]
    }
  })

  return data
120 121 122 123
}

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

fxy060608's avatar
fxy060608 已提交
124 125 126 127 128 129 130 131
function createObserver (name) {
  return function observer (newVal, oldVal) {
    if (this.$vm) {
      this.$vm[name] = newVal // 为了触发其他非 render watcher
    }
  }
}

fxy060608's avatar
fxy060608 已提交
132
export function initBehaviors (vueOptions, initBehavior) {
fxy060608's avatar
fxy060608 已提交
133 134 135 136 137 138 139 140 141 142
  const vueBehaviors = vueOptions['behaviors']
  const vueExtends = vueOptions['extends']
  const vueMixins = vueOptions['mixins']

  let vueProps = vueOptions['props']

  if (!vueProps) {
    vueOptions['props'] = vueProps = []
  }

143
  const behaviors = []
fxy060608's avatar
fxy060608 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157
  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 {
          vueProps['name'] = String
          vueProps['value'] = null
        }
      }
    })
  }
158 159
  if (isPlainObject(vueExtends) && vueExtends.props) {
    behaviors.push(
160
      initBehavior({
fxy060608's avatar
fxy060608 已提交
161
        properties: initProperties(vueExtends.props, true)
162 163 164 165 166 167 168
      })
    )
  }
  if (Array.isArray(vueMixins)) {
    vueMixins.forEach(vueMixin => {
      if (isPlainObject(vueMixin) && vueMixin.props) {
        behaviors.push(
169
          initBehavior({
fxy060608's avatar
fxy060608 已提交
170
            properties: initProperties(vueMixin.props, true)
171 172 173 174 175 176 177 178
          })
        )
      }
    })
  }
  return behaviors
}

179
function parsePropType (key, type, defaultValue, file) {
180 181 182 183 184 185
  // [String]=>String
  if (Array.isArray(type) && type.length === 1) {
    return type[0]
  }
  if (__PLATFORM__ === 'mp-baidu') {
    if (
186 187
      defaultValue === false &&
            Array.isArray(type) &&
188
            type.length === 2 &&
189 190
            type.indexOf(String) !== -1 &&
            type.indexOf(Boolean) !== -1
191
    ) { // [String,Boolean]=>Boolean
192 193 194 195
      if (file) {
        console.warn(
          `props.${key}.type should use Boolean instead of [String,Boolean] at ${file}`
        )
196
      }
197
      return Boolean
198 199 200 201 202
    }
  }
  return type
}

fxy060608's avatar
fxy060608 已提交
203
export function initProperties (props, isBehavior = false, file = '') {
204 205
  const properties = {}
  if (!isBehavior) {
fxy060608's avatar
fxy060608 已提交
206 207 208 209
    properties.vueId = {
      type: String,
      value: ''
    }
210
    properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
211 212 213 214 215 216 217 218 219 220 221 222 223
      type: null,
      value: [],
      observer: function (newVal, oldVal) {
        const $slots = Object.create(null)
        newVal.forEach(slotName => {
          $slots[slotName] = true
        })
        this.setData({
          $slots
        })
      }
    }
  }
224 225
  if (Array.isArray(props)) { // ['title']
    props.forEach(key => {
fxy060608's avatar
fxy060608 已提交
226 227 228 229
      properties[key] = {
        type: null,
        observer: createObserver(key)
      }
230 231 232 233 234 235 236 237 238
    })
  } 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:''}
        let value = opts['default']
        if (isFn(value)) {
          value = value()
        }
239

240
        opts.type = parsePropType(key, opts.type, value, file)
241

242
        properties[key] = {
243
          type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null,
fxy060608's avatar
fxy060608 已提交
244 245
          value,
          observer: createObserver(key)
246 247
        }
      } else { // content:String
248
        const type = parsePropType(key, opts, null, file)
fxy060608's avatar
fxy060608 已提交
249
        properties[key] = {
250
          type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
fxy060608's avatar
fxy060608 已提交
251 252
          observer: createObserver(key)
        }
253 254 255 256 257 258 259
      }
    })
  }
  return properties
}

function wrapper (event) {
fxy060608's avatar
fxy060608 已提交
260 261 262 263 264
  // TODO 又得兼容 mpvue 的 mp 对象
  try {
    event.mp = JSON.parse(JSON.stringify(event))
  } catch (e) {}

265 266 267 268
  event.stopPropagation = noop
  event.preventDefault = noop

  event.target = event.target || {}
fxy060608's avatar
fxy060608 已提交
269 270 271 272

  if (!hasOwn(event, 'detail')) {
    event.detail = {}
  }
fxy060608's avatar
fxy060608 已提交
273 274

  if (__PLATFORM__ === 'mp-baidu') { // mp-baidu,checked=>value
fxy060608's avatar
fxy060608 已提交
275 276 277 278 279
    if (
      isPlainObject(event.detail) &&
            hasOwn(event.detail, 'checked') &&
            !hasOwn(event.detail, 'value')
    ) {
fxy060608's avatar
fxy060608 已提交
280 281 282 283
      event.detail.value = event.detail.checked
    }
  }

fxy060608's avatar
fxy060608 已提交
284 285 286 287
  if (isPlainObject(event.detail)) {
    event.target = Object.assign({}, event.target, event.detail)
  }

288 289 290
  return event
}

fxy060608's avatar
fxy060608 已提交
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
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]

      const vFor = dataPath ? vm.__get_value(dataPath, context) : context

      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
}

328
function processEventExtra (vm, extra, event) {
fxy060608's avatar
fxy060608 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  const extraObj = {}

  if (Array.isArray(extra) && extra.length) {
    /**
         *[
         *    ['data.items', 'data.id', item.data.id],
         *    ['metas', 'id', meta.id]
         *],
         *[
         *    ['data.items', 'data.id', item.data.id],
         *    ['metas', 'id', meta.id]
         *],
         *'test'
         */
    extra.forEach((dataPath, index) => {
      if (typeof dataPath === 'string') {
        if (!dataPath) { // model,prop.sync
          extraObj['$' + index] = vm
        } else {
348 349 350 351 352 353 354
          if (dataPath === '$event') { // $event
            extraObj['$' + index] = event
          } 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 已提交
355 356 357 358 359 360 361 362 363 364
        }
      } else {
        extraObj['$' + index] = getExtraValue(vm, dataPath)
      }
    })
  }

  return extraObj
}

fxy060608's avatar
fxy060608 已提交
365 366 367 368 369 370 371 372 373
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 已提交
374
function processEventArgs (vm, event, args = [], extra = [], isCustom, methodName) {
fxy060608's avatar
fxy060608 已提交
375
  let isCustomMPEvent = false // wxcomponent 组件,传递原始 event 对象
376
  if (isCustom) { // 自定义事件
fxy060608's avatar
fxy060608 已提交
377
    isCustomMPEvent = event.currentTarget &&
378
            event.currentTarget.dataset &&
379
            event.currentTarget.dataset.comType === 'wx'
fxy060608's avatar
fxy060608 已提交
380 381 382 383
    if (!args.length) { // 无参数,直接传入 event 或 detail 数组
      if (isCustomMPEvent) {
        return [event]
      }
fxy060608's avatar
fxy060608 已提交
384
      return event.detail.__args__ || event.detail
385
    }
386
  }
fxy060608's avatar
fxy060608 已提交
387

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

390 391 392
  const ret = []
  args.forEach(arg => {
    if (arg === '$event') {
fxy060608's avatar
fxy060608 已提交
393 394 395
      if (methodName === '__set_model' && !isCustom) { // input v-model value
        ret.push(event.target.value)
      } else {
fxy060608's avatar
fxy060608 已提交
396
        if (isCustom && !isCustomMPEvent) {
fxy060608's avatar
fxy060608 已提交
397
          ret.push(event.detail.__args__[0])
fxy060608's avatar
fxy060608 已提交
398 399 400
        } else { // wxcomponent 组件或内置组件
          ret.push(event)
        }
fxy060608's avatar
fxy060608 已提交
401
      }
402
    } else {
fxy060608's avatar
fxy060608 已提交
403 404 405
      if (Array.isArray(arg) && arg[0] === 'o') {
        ret.push(getObjByArray(arg))
      } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
fxy060608's avatar
fxy060608 已提交
406 407 408 409
        ret.push(extraObj[arg])
      } else {
        ret.push(arg)
      }
410 411 412 413 414 415 416 417 418
    }
  })

  return ret
}

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

fxy060608's avatar
fxy060608 已提交
419 420 421 422 423 424 425 426 427 428 429
function isMatchEventType (eventType, optType) {
  return (eventType === optType) ||
        (
          optType === 'regionchange' &&
            (
              eventType === 'begin' ||
                eventType === 'end'
            )
        )
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
export function handleEvent (event) {
  event = wrapper(event)

  // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
  const eventOpts = (event.currentTarget || event.target).dataset.eventOpts
  if (!eventOpts) {
    return console.warn(`事件信息不存在`)
  }

  // [['handle',[1,2,a]],['handle1',[1,2,a]]]
  const eventType = event.type
  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 已提交
450
    if (eventsArray && isMatchEventType(eventType, type)) {
451
      eventsArray.forEach(eventArray => {
452
        const methodName = eventArray[0]
fxy060608's avatar
fxy060608 已提交
453
        if (methodName) {
fxy060608's avatar
fxy060608 已提交
454 455 456 457 458 459 460 461 462
          let handlerCtx = this.$vm
          if (
            handlerCtx.$options.generic &&
                        handlerCtx.$parent &&
                        handlerCtx.$parent.$parent
          ) { // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots
            handlerCtx = handlerCtx.$parent.$parent
          }
          const handler = handlerCtx[methodName]
fxy060608's avatar
fxy060608 已提交
463 464 465 466 467 468 469 470
          if (!isFn(handler)) {
            throw new Error(` _vm.${methodName} is not a function`)
          }
          if (isOnce) {
            if (handler.once) {
              return
            }
            handler.once = true
471
          }
fxy060608's avatar
fxy060608 已提交
472
          handler.apply(handlerCtx, processEventArgs(
fxy060608's avatar
fxy060608 已提交
473 474 475 476 477 478 479
            this.$vm,
            event,
            eventArray[1],
            eventArray[2],
            isCustom,
            methodName
          ))
480 481 482 483 484
        }
      })
    }
  })
}