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

8 9 10 11
import {
  initBehavior
} from 'uni-platform/runtime/wrapper/index'

fxy060608's avatar
fxy060608 已提交
12
export function initMocks (vm, mocks) {
13
  const mpInstance = vm.$mp[vm.mpType]
fxy060608's avatar
fxy060608 已提交
14
  mocks.forEach(mock => {
15 16 17 18 19 20
    if (hasOwn(mpInstance, mock)) {
      vm[mock] = mpInstance[mock]
    }
  })
}

21
export function initHooks (mpOptions, hooks) {
22 23
  hooks.forEach(hook => {
    mpOptions[hook] = function (args) {
24
      return this.$vm.__call_hook(hook, args)
25 26 27 28
    }
  })
}

fxy060608's avatar
fxy060608 已提交
29
export function getData (vueOptions, context) {
fxy060608's avatar
fxy060608 已提交
30 31
  let data = vueOptions.data || {}
  const methods = vueOptions.methods || {}
32 33 34

  if (typeof data === 'function') {
    try {
fxy060608's avatar
fxy060608 已提交
35
      data = data.call(context) // 支持 Vue.prototype 上挂的数据
36
    } catch (e) {
37 38 39
      if (process.env.VUE_APP_DEBUG) {
        console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data)
      }
40
    }
41 42 43 44 45
  } else {
    try {
      // 对 data 格式化
      data = JSON.parse(JSON.stringify(data))
    } catch (e) {}
46 47 48 49
  }

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

52
  Object.keys(methods).forEach(methodName => {
fxy060608's avatar
fxy060608 已提交
53
    if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
54 55 56 57 58
      data[methodName] = methods[methodName]
    }
  })

  return data
59 60 61 62
}

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

fxy060608's avatar
fxy060608 已提交
63 64 65 66 67 68 69 70
function createObserver (name) {
  return function observer (newVal, oldVal) {
    if (this.$vm) {
      this.$vm[name] = newVal // 为了触发其他非 render watcher
    }
  }
}

71
export function getBehaviors (vueOptions) {
fxy060608's avatar
fxy060608 已提交
72 73 74 75 76 77 78 79 80 81
  const vueBehaviors = vueOptions['behaviors']
  const vueExtends = vueOptions['extends']
  const vueMixins = vueOptions['mixins']

  let vueProps = vueOptions['props']

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

82
  const behaviors = []
fxy060608's avatar
fxy060608 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
  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
        }
      }
    })
  }
97 98
  if (isPlainObject(vueExtends) && vueExtends.props) {
    behaviors.push(
99
      initBehavior({
100 101 102 103 104 105 106 107
        properties: getProperties(vueExtends.props, true)
      })
    )
  }
  if (Array.isArray(vueMixins)) {
    vueMixins.forEach(vueMixin => {
      if (isPlainObject(vueMixin) && vueMixin.props) {
        behaviors.push(
108
          initBehavior({
109 110 111 112 113 114 115 116 117
            properties: getProperties(vueMixin.props, true)
          })
        )
      }
    })
  }
  return behaviors
}

118
function parsePropType (key, type, defaultValue, file) {
119 120 121 122 123 124
  // [String]=>String
  if (Array.isArray(type) && type.length === 1) {
    return type[0]
  }
  if (__PLATFORM__ === 'mp-baidu') {
    if (
125 126
      defaultValue === false &&
            Array.isArray(type) &&
127
            type.length === 2 &&
128 129
            type.indexOf(String) !== -1 &&
            type.indexOf(Boolean) !== -1
130
    ) { // [String,Boolean]=>Boolean
131 132 133 134
      if (file) {
        console.warn(
          `props.${key}.type should use Boolean instead of [String,Boolean] at ${file}`
        )
135
      }
136
      return Boolean
137 138 139 140 141 142
    }
  }
  return type
}

export function getProperties (props, isBehavior = false, file = '') {
143 144 145
  const properties = {}
  if (!isBehavior) {
    properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
146 147 148 149 150 151 152 153 154 155 156 157 158
      type: null,
      value: [],
      observer: function (newVal, oldVal) {
        const $slots = Object.create(null)
        newVal.forEach(slotName => {
          $slots[slotName] = true
        })
        this.setData({
          $slots
        })
      }
    }
  }
159 160
  if (Array.isArray(props)) { // ['title']
    props.forEach(key => {
fxy060608's avatar
fxy060608 已提交
161 162 163 164
      properties[key] = {
        type: null,
        observer: createObserver(key)
      }
165 166 167 168 169 170 171 172 173
    })
  } 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()
        }
174

175
        opts.type = parsePropType(key, opts.type, value, file)
176

177
        properties[key] = {
178
          type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null,
fxy060608's avatar
fxy060608 已提交
179 180
          value,
          observer: createObserver(key)
181 182
        }
      } else { // content:String
183
        const type = parsePropType(key, opts, null, file)
fxy060608's avatar
fxy060608 已提交
184
        properties[key] = {
185
          type: PROP_TYPES.indexOf(type) !== -1 ? type : null,
fxy060608's avatar
fxy060608 已提交
186 187
          observer: createObserver(key)
        }
188 189 190 191 192 193 194
      }
    })
  }
  return properties
}

function wrapper (event) {
fxy060608's avatar
fxy060608 已提交
195 196 197 198 199
  // TODO 又得兼容 mpvue 的 mp 对象
  try {
    event.mp = JSON.parse(JSON.stringify(event))
  } catch (e) {}

200 201 202 203
  event.stopPropagation = noop
  event.preventDefault = noop

  event.target = event.target || {}
fxy060608's avatar
fxy060608 已提交
204 205 206 207

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

  if (__PLATFORM__ === 'mp-baidu') { // mp-baidu,checked=>value
fxy060608's avatar
fxy060608 已提交
210 211 212 213 214
    if (
      isPlainObject(event.detail) &&
            hasOwn(event.detail, 'checked') &&
            !hasOwn(event.detail, 'value')
    ) {
fxy060608's avatar
fxy060608 已提交
215 216 217 218
      event.detail.value = event.detail.checked
    }
  }

fxy060608's avatar
fxy060608 已提交
219 220 221 222
  if (isPlainObject(event.detail)) {
    event.target = Object.assign({}, event.target, event.detail)
  }

223 224 225
  return event
}

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

263
function processEventExtra (vm, extra, event) {
fxy060608's avatar
fxy060608 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  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 {
283 284 285 286 287 288 289
          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 已提交
290 291 292 293 294 295 296 297 298 299
        }
      } else {
        extraObj['$' + index] = getExtraValue(vm, dataPath)
      }
    })
  }

  return extraObj
}

fxy060608's avatar
fxy060608 已提交
300 301 302 303 304 305 306 307 308
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 已提交
309
function processEventArgs (vm, event, args = [], extra = [], isCustom, methodName) {
fxy060608's avatar
fxy060608 已提交
310
  let isCustomMPEvent = false // wxcomponent 组件,传递原始 event 对象
311
  if (isCustom) { // 自定义事件
fxy060608's avatar
fxy060608 已提交
312
    isCustomMPEvent = event.currentTarget &&
313
            event.currentTarget.dataset &&
314
            event.currentTarget.dataset.comType === 'wx'
fxy060608's avatar
fxy060608 已提交
315 316 317 318
    if (!args.length) { // 无参数,直接传入 event 或 detail 数组
      if (isCustomMPEvent) {
        return [event]
      }
fxy060608's avatar
fxy060608 已提交
319
      return event.detail.__args__ || event.detail
320
    }
321
  }
fxy060608's avatar
fxy060608 已提交
322

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

325 326 327
  const ret = []
  args.forEach(arg => {
    if (arg === '$event') {
fxy060608's avatar
fxy060608 已提交
328 329 330
      if (methodName === '__set_model' && !isCustom) { // input v-model value
        ret.push(event.target.value)
      } else {
fxy060608's avatar
fxy060608 已提交
331
        if (isCustom && !isCustomMPEvent) {
fxy060608's avatar
fxy060608 已提交
332
          ret.push(event.detail.__args__[0])
fxy060608's avatar
fxy060608 已提交
333 334 335
        } else { // wxcomponent 组件或内置组件
          ret.push(event)
        }
fxy060608's avatar
fxy060608 已提交
336
      }
337
    } else {
fxy060608's avatar
fxy060608 已提交
338 339 340
      if (Array.isArray(arg) && arg[0] === 'o') {
        ret.push(getObjByArray(arg))
      } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
fxy060608's avatar
fxy060608 已提交
341 342 343 344
        ret.push(extraObj[arg])
      } else {
        ret.push(arg)
      }
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
    }
  })

  return ret
}

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

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

    if (eventsArray && eventType === type) {
      eventsArray.forEach(eventArray => {
376
        const methodName = eventArray[0]
fxy060608's avatar
fxy060608 已提交
377 378 379 380 381 382 383 384 385 386
        if (methodName) {
          const handler = this.$vm[methodName]
          if (!isFn(handler)) {
            throw new Error(` _vm.${methodName} is not a function`)
          }
          if (isOnce) {
            if (handler.once) {
              return
            }
            handler.once = true
387
          }
fxy060608's avatar
fxy060608 已提交
388 389 390 391 392 393 394 395
          handler.apply(this.$vm, processEventArgs(
            this.$vm,
            event,
            eventArray[1],
            eventArray[2],
            isCustom,
            methodName
          ))
396 397 398 399 400 401
        }
      })
    }
  })
}

fxy060608's avatar
fxy060608 已提交
402 403 404 405 406 407 408 409 410 411 412 413
function baiduComponentDestroy ($vm) {
  $vm.$children.forEach(childVm => {
    childVm.$mp.component.detached()
  })
  $vm.$mp.component.detached()
}

export function baiduPageDestroy ($vm) {
  $vm.$destroy()
  $vm.$children.forEach(childVm => {
    baiduComponentDestroy(childVm)
  })
414
}