app.js 6.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import {
  callAppHook
} from 'uni-core/service/plugins/util'

fxy060608's avatar
fxy060608 已提交
5
import initOn from 'uni-core/service/bridge/on'
6

fxy060608's avatar
init v3  
fxy060608 已提交
7
import {
8 9 10
  NETWORK_TYPES,
  TEMP_PATH,
  TEMP_PATH_BASE
fxy060608's avatar
init v3  
fxy060608 已提交
11 12
} from '../api/constants'

fxy060608's avatar
fxy060608 已提交
13 14 15 16 17
import {
  getCurrentPages
} from './page'

import {
18
  consumePlusMessage
fxy060608's avatar
fxy060608 已提交
19 20
} from './plus-message'

21 22
import tabBar from './tab-bar'

Q
qiang 已提交
23
import {
d-u-a's avatar
d-u-a 已提交
24 25
  publish,
  requireNativePlugin
Q
qiang 已提交
26
} from '../bridge'
fxy060608's avatar
fxy060608 已提交
27

fxy060608's avatar
init v3  
fxy060608 已提交
28 29 30 31 32 33
import {
  initSubscribeHandlers
} from './subscribe-handlers'

import {
  perf
fxy060608's avatar
fxy060608 已提交
34
} from './perf'
雪洛's avatar
雪洛 已提交
35 36 37 38

import {
  backbuttonListener
} from './backbutton'
fxy060608's avatar
fxy060608 已提交
39

fxy060608's avatar
init v3  
fxy060608 已提交
40
let appCtx
fxy060608's avatar
fxy060608 已提交
41

fxy060608's avatar
fxy060608 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
const defaultApp = {
  globalData: {}
}

export function getApp ({
  allowDefault = false
} = {}) {
  if (appCtx) { // 真实的 App 已初始化
    return appCtx
  }
  if (allowDefault) { // 返回默认实现
    return defaultApp
  }
fxy060608's avatar
fxy060608 已提交
55 56 57
  console.error(
    '[warn]: getApp() 操作失败,v3模式加速了首页 nvue 的启动速度,当在首页 nvue 中使用 getApp() 不一定可以获取真正的 App 对象。详情请参考:https://uniapp.dcloud.io/collocation/frame/window?id=getapp'
  )
fxy060608's avatar
fxy060608 已提交
58 59
}

fxy060608's avatar
fxy060608 已提交
60
function initGlobalListeners () {
61
  const globalEvent = requireNativePlugin('globalEvent')
fxy060608's avatar
fxy060608 已提交
62
  const emit = UniServiceJSBridge.emit
fxy060608's avatar
fxy060608 已提交
63

fxy060608's avatar
fxy060608 已提交
64 65 66 67
  if (weex.config.preload) {
    if (process.env.NODE_ENV !== 'production') {
      console.log('[uni-app] preload.addEventListener.backbutton')
    }
fxy060608's avatar
fxy060608 已提交
68
    plus.key.addEventListener('backbutton', backbuttonListener)
fxy060608's avatar
fxy060608 已提交
69 70 71 72 73 74
  } else {
    // splashclosed 时开始监听 backbutton
    plus.globalEvent.addEventListener('splashclosed', () => {
      plus.key.addEventListener('backbutton', backbuttonListener)
    })
  }
fxy060608's avatar
fxy060608 已提交
75 76 77 78 79 80 81 82 83 84 85

  plus.globalEvent.addEventListener('pause', () => {
    emit('onAppEnterBackground')
  })

  plus.globalEvent.addEventListener('resume', () => {
    emit('onAppEnterForeground')
  })

  plus.globalEvent.addEventListener('netchange', () => {
    const networkType = NETWORK_TYPES[plus.networkinfo.getCurrentType()]
Q
qiang 已提交
86
    publish('onNetworkStatusChange', {
fxy060608's avatar
fxy060608 已提交
87 88 89
      isConnected: networkType !== 'none',
      networkType
    })
90 91 92 93 94 95
  })

  plus.globalEvent.addEventListener('KeyboardHeightChange', function (event) {
    publish('onKeyboardHeightChange', {
      height: event.height
    })
fxy060608's avatar
fxy060608 已提交
96 97
  })

98 99 100 101 102 103 104 105 106 107 108
  globalEvent.addEventListener('uistylechange', function (event) {
    const args = {
      theme: event.uistyle
    }

    callAppHook(appCtx, 'onThemeChange', args)
    publish('onThemeChange', args)

    // 兼容旧版本 API
    publish('onUIStyleChange', {
      style: event.uistyle
fxy060608's avatar
fxy060608 已提交
109 110 111
    })
  })

fxy060608's avatar
fxy060608 已提交
112 113
  globalEvent.addEventListener('uniMPNativeEvent', function (event) {
    publish('uniMPNativeEvent', event)
fxy060608's avatar
fxy060608 已提交
114
  })
115

fxy060608's avatar
fxy060608 已提交
116 117 118
  plus.globalEvent.addEventListener('plusMessage', onPlusMessage)

  // nvue webview post message
d-u-a's avatar
d-u-a 已提交
119
  plus.globalEvent.addEventListener('WebviewPostMessage', onPlusMessage)
fxy060608's avatar
fxy060608 已提交
120 121
}

d-u-a's avatar
d-u-a 已提交
122 123 124 125 126 127 128 129
function onPlusMessage (e) {
  if (process.env.NODE_ENV !== 'production') {
    console.log('[plusMessage]:[' + Date.now() + ']' + JSON.stringify(e.data))
  }
  if (e.data && e.data.type) {
    const type = e.data.type
    consumePlusMessage(type, e.data.args || {})
  }
fxy060608's avatar
fxy060608 已提交
130 131
}

fxy060608's avatar
fxy060608 已提交
132
function initAppLaunch (appVm) {
fxy060608's avatar
fxy060608 已提交
133 134 135 136 137 138 139 140
  const args = {
    path: __uniConfig.entryPagePath,
    query: {},
    scene: 1001
  }

  callAppHook(appVm, 'onLaunch', args)
  callAppHook(appVm, 'onShow', args)
fxy060608's avatar
fxy060608 已提交
141 142
}

fxy060608's avatar
fxy060608 已提交
143
function initTabBar () {
144
  if (!__uniConfig.tabBar || !__uniConfig.tabBar.list || !__uniConfig.tabBar.list.length) {
fxy060608's avatar
fxy060608 已提交
145 146 147
    return
  }

148 149 150
  __uniConfig.tabBar.selected = 0

  const selected = __uniConfig.tabBar.list.findIndex(page => page.pagePath === __uniConfig.entryPagePath)
fxy060608's avatar
fxy060608 已提交
151

fxy060608's avatar
fxy060608 已提交
152 153 154 155 156 157 158 159 160 161 162 163
  tabBar.init(__uniConfig.tabBar, (item, index) => {
    uni.switchTab({
      url: '/' + item.pagePath,
      openType: 'switchTab',
      from: 'tabBar',
      success () {
        UniServiceJSBridge.emit('onTabItemTap', {
          index,
          text: item.text,
          pagePath: item.pagePath
        })
      }
fxy060608's avatar
fxy060608 已提交
164
    })
fxy060608's avatar
fxy060608 已提交
165
  })
fxy060608's avatar
fxy060608 已提交
166 167 168 169 170 171

  if (selected !== -1) {
    // 取当前 tab 索引值
    __uniConfig.tabBar.selected = selected
    selected !== 0 && tabBar.switchTab(__uniConfig.entryPagePath)
  }
fxy060608's avatar
fxy060608 已提交
172 173
}

174 175 176 177
function initEntryPage () {
  let entryPagePath
  let entryPageQuery

fxy060608's avatar
fxy060608 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  const weexPlus = weex.requireModule('plus')

  if (weexPlus.getRedirectInfo) {
    const info = weexPlus.getRedirectInfo() || {}
    entryPagePath = info.path
    entryPageQuery = info.query ? ('?' + info.query) : ''
  } else {
    const argsJsonStr = plus.runtime.arguments
    if (!argsJsonStr) {
      return
    }
    try {
      const args = JSON.parse(argsJsonStr)
      entryPagePath = args.path || args.pathName
      entryPageQuery = args.query ? ('?' + args.query) : ''
    } catch (e) {}
  }

196
  if (!entryPagePath || entryPagePath === __uniConfig.entryPagePath) {
fxy060608's avatar
fxy060608 已提交
197 198
    return
  }
199 200 201

  const entryRoute = '/' + entryPagePath
  const routeOptions = __uniRoutes.find(route => route.path === entryRoute)
fxy060608's avatar
fxy060608 已提交
202 203 204
  if (!routeOptions) {
    return
  }
205

fxy060608's avatar
fxy060608 已提交
206 207 208
  if (!routeOptions.meta.isTabBar) {
    __uniConfig.realEntryPagePath = __uniConfig.realEntryPagePath || __uniConfig.entryPagePath
  }
209 210 211 212

  __uniConfig.entryPagePath = entryPagePath
  __uniConfig.entryPageQuery = entryPageQuery

fxy060608's avatar
fxy060608 已提交
213
  if (process.env.NODE_ENV !== 'production') {
214
    console.log(`[uni-app] entryPagePath(${entryPagePath + entryPageQuery})`)
fxy060608's avatar
fxy060608 已提交
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
export function clearTempFile () {
  // 统一处理路径
  function getPath (path) {
    path = path.replace(/\/$/, '')
    return path.indexOf('_') === 0 ? plus.io.convertLocalFileSystemURL(path) : path
  }
  var basePath = getPath(TEMP_PATH_BASE)
  var tempPath = getPath(TEMP_PATH)
  // 获取父目录
  var dirPath = tempPath.split('/')
  dirPath.pop()
  dirPath = dirPath.join('/')
  plus.io.resolveLocalFileSystemURL(plus.io.convertAbsoluteFileSystem(dirPath), entry => {
    var reader = entry.createReader()
    reader.readEntries(function (entries) {
      if (entries && entries.length) {
        entries.forEach(function (entry) {
          if (entry.isDirectory && entry.fullPath.indexOf(basePath) === 0 && entry.fullPath
            .indexOf(tempPath) !== 0) {
            entry.removeRecursively()
          }
        })
      }
    })
  })
}

fxy060608's avatar
fxy060608 已提交
245
export function registerApp (appVm) {
fxy060608's avatar
fxy060608 已提交
246
  if (process.env.NODE_ENV !== 'production') {
fxy060608's avatar
fxy060608 已提交
247
    console.log('[uni-app] registerApp')
fxy060608's avatar
fxy060608 已提交
248
  }
fxy060608's avatar
fxy060608 已提交
249 250

  appCtx = appVm
fxy060608's avatar
fxy060608 已提交
251
  appCtx.$vm = appVm
252

fxy060608's avatar
fxy060608 已提交
253 254 255 256 257
  Object.assign(appCtx, defaultApp) // 拷贝默认实现

  const globalData = appVm.$options.globalData || {}
  // merge globalData
  appCtx.globalData = Object.assign(globalData, appCtx.globalData)
fxy060608's avatar
fxy060608 已提交
258

fxy060608's avatar
fxy060608 已提交
259 260 261 262 263
  initOn(UniServiceJSBridge.on, {
    getApp,
    getCurrentPages
  })

264
  initEntryPage()
fxy060608's avatar
fxy060608 已提交
265

fxy060608's avatar
init v3  
fxy060608 已提交
266
  initTabBar()
fxy060608's avatar
fxy060608 已提交
267 268

  initGlobalListeners()
fxy060608's avatar
fxy060608 已提交
269

fxy060608's avatar
init v3  
fxy060608 已提交
270 271 272 273
  initSubscribeHandlers()

  initAppLaunch(appVm)

274 275 276
  // 10s后清理临时文件
  setTimeout(clearTempFile, 10000)

fxy060608's avatar
fxy060608 已提交
277
  __uniConfig.ready = true
fxy060608's avatar
fxy060608 已提交
278

fxy060608's avatar
init v3  
fxy060608 已提交
279
  process.env.NODE_ENV !== 'production' && perf('registerApp')
280
}