index.js 13.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import { createUniInstance } from './uni';

fxy060608's avatar
fxy060608 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
function callHook (vm, hook, params) {
  return (vm.$vm || vm).__call_hook(hook, params)
}

function callAppHook (vm, hook, params) {
  if (hook !== 'onError') {
    console.debug(`App:${hook} have been invoked` + (params ? ` ${JSON.stringify(params)}` : ''));
  }
  return (vm.$vm || vm).__call_hook(hook, params)
}

function callPageHook (vm, hook, params) {
  if (hook !== 'onPageScroll') {
    console.debug(`${vm.$page.route}[${vm.$page.id}]:${hook} have been invoked`);
  }
  return callHook(vm, hook, params)
}

fxy060608's avatar
fxy060608 已提交
21 22
let appCtx;

fxy060608's avatar
fxy060608 已提交
23 24 25 26 27 28 29 30 31 32 33
const NETWORK_TYPES = [
  'unknown',
  'none',
  'ethernet',
  'wifi',
  '2g',
  '3g',
  '4g'
];

function getApp () {
fxy060608's avatar
fxy060608 已提交
34 35 36
  return appCtx
}

fxy060608's avatar
fxy060608 已提交
37
function initGlobalListeners ({
fxy060608's avatar
fxy060608 已提交
38
  uni,
fxy060608's avatar
fxy060608 已提交
39 40
  plus,
  UniServiceJSBridge
fxy060608's avatar
fxy060608 已提交
41
}) {
fxy060608's avatar
fxy060608 已提交
42 43
  const emit = UniServiceJSBridge.emit;

fxy060608's avatar
fxy060608 已提交
44
  plus.key.addEventListener('backbutton', () => {
fxy060608's avatar
fxy060608 已提交
45 46 47
    uni.navigateBack({
      from: 'backbutton'
    });
fxy060608's avatar
fxy060608 已提交
48
  });
fxy060608's avatar
fxy060608 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

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

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

  plus.globalEvent.addEventListener('netchange', () => {
    const networkType = NETWORK_TYPES[plus.networkinfo.getCurrentType()];
    emit('onNetworkStatusChange', {
      isConnected: networkType !== 'none',
      networkType
    });
  });
}

function initAppLaunch (appVm, {
  __uniConfig
fxy060608's avatar
fxy060608 已提交
69
}) {
fxy060608's avatar
fxy060608 已提交
70 71 72 73 74 75 76 77
  const args = {
    path: __uniConfig.entryPagePath,
    query: {},
    scene: 1001
  };

  callAppHook(appVm, 'onLaunch', args);
  callAppHook(appVm, 'onShow', args);
fxy060608's avatar
fxy060608 已提交
78 79 80 81 82 83
}

function registerApp (appVm, instanceContext) {
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] registerApp`);
  }
fxy060608's avatar
fxy060608 已提交
84

fxy060608's avatar
fxy060608 已提交
85
  appCtx = appVm;
fxy060608's avatar
fxy060608 已提交
86 87 88 89 90 91 92 93 94 95

  initAppLaunch(appVm, instanceContext);

  initGlobalListeners(instanceContext);
}

const _toString = Object.prototype.toString;

function isPlainObject (obj) {
  return _toString.call(obj) === '[object Object]'
fxy060608's avatar
fxy060608 已提交
96 97
}

fxy060608's avatar
fxy060608 已提交
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
function parseTitleNView (routeOptions) {
  const windowOptions = routeOptions.window;
  const titleNView = windowOptions.titleNView;
  if ( // 无头
    titleNView === false ||
    titleNView === 'false' ||
    (
      windowOptions.navigationStyle === 'custom' &&
      !isPlainObject(titleNView)
    )
  ) {
    return false
  }

  const ret = {
    autoBackButton: !routeOptions.meta.isQuit,
    backgroundColor: windowOptions.navigationBarBackgroundColor || '#000000',
    titleText: windowOptions.navigationBarTitleText || '',
    titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff'
  };

  if (isPlainObject(titleNView)) {
    return Object.assign(ret, titleNView)
  }

  return ret
}

function parsePullToRefresh (routeOptions, {
  plus
}) {
  const windowOptions = routeOptions.window;

  if (windowOptions.enablePullDownRefresh) {
    const pullToRefreshStyles = Object.create(null);
    // 初始化默认值
    if (plus.os.name === 'Android') {
      Object.assign(pullToRefreshStyles, {
        support: true,
        style: 'circle'
      });
    } else {
      Object.assign(pullToRefreshStyles, {
        support: true,
        style: 'default',
        height: '50px',
        range: '200px',
        contentdown: {
          caption: ''
        },
        contentover: {
          caption: ''
        },
        contentrefresh: {
          caption: ''
        }
      });
    }

    if (windowOptions.backgroundTextStyle) {
      pullToRefreshStyles.color = windowOptions.backgroundTextStyle;
      pullToRefreshStyles.snowColor = windowOptions.backgroundTextStyle;
    }

    Object.assign(pullToRefreshStyles, windowOptions.pullToRefresh || {});

    return pullToRefreshStyles
  }
}

const WEBVIEW_STYLE_BLACKLIST = [
  'navigationBarBackgroundColor',
  'navigationBarTextStyle',
  'navigationBarTitleText',
  'navigationBarShadow',
  'navigationStyle',
  'disableScroll',
  'backgroundColor',
  'backgroundTextStyle',
  'enablePullDownRefresh',
  'onReachBottomDistance',
  'usingComponents',
  // 需要解析的
  'titleNView',
  'pullToRefresh'
fxy060608's avatar
fxy060608 已提交
183 184
];

fxy060608's avatar
fxy060608 已提交
185 186 187 188 189 190
function parseWebviewStyle (id, path, routeOptions = {}, instanceContext) {
  const {
    __uniConfig
  } = instanceContext;

  const webviewStyle = Object.create(null);
fxy060608's avatar
fxy060608 已提交
191

fxy060608's avatar
fxy060608 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  // 合并
  const windowOptions = Object.assign(
    JSON.parse(JSON.stringify(__uniConfig.window || {})),
    routeOptions.window || {}
  );

  Object.keys(windowOptions).forEach(name => {
    if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
      webviewStyle[name] = windowOptions[name];
    }
  });

  const titleNView = parseTitleNView(routeOptions);
  if (titleNView) {
    if (id === 1 && __uniConfig.realEntryPagePath === path) {
      titleNView.autoBackButton = true;
fxy060608's avatar
fxy060608 已提交
208
    }
fxy060608's avatar
fxy060608 已提交
209
    webviewStyle.titleNView = titleNView;
fxy060608's avatar
fxy060608 已提交
210 211
  }

fxy060608's avatar
fxy060608 已提交
212 213 214 215 216 217 218
  const pullToRefresh = parsePullToRefresh(routeOptions, instanceContext);
  if (pullToRefresh) {
    if (pullToRefresh.style === 'circle') {
      webviewStyle.bounce = 'none';
    }
    webviewStyle.pullToRefresh = pullToRefresh;
  }
fxy060608's avatar
fxy060608 已提交
219

fxy060608's avatar
fxy060608 已提交
220 221 222 223 224 225 226 227 228
  // 不支持 hide
  if (webviewStyle.popGesture === 'hide') {
    delete webviewStyle.popGesture;
  }

  // TODO 下拉刷新

  if (path && routeOptions.meta.isNVue) {
    webviewStyle.uniNView = {
fxy060608's avatar
fxy060608 已提交
229
      path,
fxy060608's avatar
fxy060608 已提交
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
      defaultFontSize: __uniConfig.defaultFontSize,
      viewport: __uniConfig.viewport
    };
  }

  return webviewStyle
}

function parseNavigationBar (webviewStyle) {
  let titleText = '';
  let textColor = '';
  let backgroundColor = '';
  const titleNView = webviewStyle.titleNView;
  if (titleNView) {
    titleText = titleNView.titleText || '';
    textColor = titleNView.textColor || '';
    backgroundColor = titleNView.backgroundColor || '';
  }
  return {
    titleText,
    textColor,
    backgroundColor
  }
}

let id = 2;

const WEBVIEW_LISTENERS = {
  'pullToRefresh': 'onPullDownRefresh',
  'titleNViewSearchInputChanged': 'onNavigationBarSearchInputChanged',
  'titleNViewSearchInputConfirmed': 'onNavigationBarSearchInputConfirmed',
  'titleNViewSearchInputClicked': 'onNavigationBarSearchInputClicked'
};

function createWebview (path, instanceContext, routeOptions) {
  const webviewId = id++;
  const webviewStyle = parseWebviewStyle(
    webviewId,
    path,
    routeOptions,
    instanceContext
  );
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] createWebview`, webviewId, path, webviewStyle);
  }
  const webview = instanceContext.plus.webview.create('', String(webviewId), webviewStyle);

  webview.$navigationBar = parseNavigationBar(webviewStyle);

  return webview
fxy060608's avatar
fxy060608 已提交
280 281
}

fxy060608's avatar
fxy060608 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
function initWebview (webview, instanceContext, routeOptions) {
  if (isPlainObject(routeOptions)) {
    const webviewStyle = parseWebviewStyle(
      parseInt(webview.id),
      '',
      routeOptions,
      instanceContext
    );
    if (process.env.NODE_ENV !== 'production') {
      console.log(`[uni-app] updateWebview`, webviewStyle);
    }

    webview.$navigationBar = parseNavigationBar(webviewStyle);

    webview.setStyle(webviewStyle);
  }
fxy060608's avatar
fxy060608 已提交
298 299 300 301 302 303

  const {
    on,
    emit
  } = instanceContext.UniServiceJSBridge;

fxy060608's avatar
fxy060608 已提交
304
  // TODO subNVues
fxy060608's avatar
fxy060608 已提交
305 306
  Object.keys(WEBVIEW_LISTENERS).forEach(name => {
    webview.addEventListener(name, (e) => {
fxy060608's avatar
fxy060608 已提交
307
      emit(WEBVIEW_LISTENERS[name], e, parseInt(webview.id));
fxy060608's avatar
fxy060608 已提交
308 309
    });
  });
fxy060608's avatar
fxy060608 已提交
310

fxy060608's avatar
fxy060608 已提交
311 312 313 314 315 316
  // TODO 应该结束之前未完成的下拉刷新
  on(webview.id + '.startPullDownRefresh', () => {
    webview.beginPullToRefresh();
  });

  on(webview.id + '.stopPullDownRefresh', () => {
fxy060608's avatar
fxy060608 已提交
317 318 319 320 321 322
    webview.endPullToRefresh();
  });

  return webview
}

fxy060608's avatar
fxy060608 已提交
323
const pages = [];
fxy060608's avatar
fxy060608 已提交
324

fxy060608's avatar
fxy060608 已提交
325
function getCurrentPages () {
fxy060608's avatar
fxy060608 已提交
326
  return pages
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
}
/**
 * @param {Object} pageVm
 *
 * page.beforeCreate 时添加 page
 * page.beforeDestroy 时移出 page
 *
 * page.viewappear  onShow
 * page.viewdisappear onHide
 *
 * navigateTo
 * redirectTo
 *
 *
 *
 *
 *
 *
fxy060608's avatar
fxy060608 已提交
345 346
 */

fxy060608's avatar
fxy060608 已提交
347 348 349
/**
 * 首页需要主动registerPage,二级页面路由跳转时registerPage
 */
fxy060608's avatar
fxy060608 已提交
350 351 352 353
function registerPage ({
  path,
  webview
}, instanceContext) {
fxy060608's avatar
fxy060608 已提交
354
  const routeOptions = JSON.parse(JSON.stringify(instanceContext.__uniRoutes.find(route => route.path === path)));
fxy060608's avatar
fxy060608 已提交
355 356

  if (!webview) {
fxy060608's avatar
fxy060608 已提交
357
    webview = createWebview(path, instanceContext, routeOptions);
fxy060608's avatar
fxy060608 已提交
358 359
  }

fxy060608's avatar
fxy060608 已提交
360 361 362
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] registerPage`, path, webview.id);
  }
fxy060608's avatar
fxy060608 已提交
363

fxy060608's avatar
fxy060608 已提交
364
  initWebview(webview, instanceContext, webview.id === '1' && routeOptions);
fxy060608's avatar
fxy060608 已提交
365

fxy060608's avatar
fxy060608 已提交
366 367 368 369
  const route = path.slice(1);

  webview.__uniapp_route = route;

fxy060608's avatar
fxy060608 已提交
370
  pages.push({
fxy060608's avatar
fxy060608 已提交
371
    route,
fxy060608's avatar
fxy060608 已提交
372 373 374
    $getAppWebview () {
      return webview
    },
fxy060608's avatar
fxy060608 已提交
375 376 377 378 379
    $page: {
      id: parseInt(webview.id),
      meta: routeOptions.meta,
      path,
      route
fxy060608's avatar
fxy060608 已提交
380
    }
fxy060608's avatar
fxy060608 已提交
381
  });
fxy060608's avatar
fxy060608 已提交
382 383

  return webview
fxy060608's avatar
fxy060608 已提交
384 385
}

386 387 388 389
const uniConfig = Object.create(null);
const uniRoutes = [];

function parseRoutes (config) {
fxy060608's avatar
fxy060608 已提交
390
  uniRoutes.length = 0;
391 392 393 394
  /* eslint-disable no-mixed-operators */
  const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath);

  Object.keys(config.page).forEach(function (pagePath) {
fxy060608's avatar
fxy060608 已提交
395 396
    const isTabBar = tabBarList.indexOf(pagePath) !== -1;
    const isQuit = isTabBar || (config.pages[0] === pagePath);
fxy060608's avatar
fxy060608 已提交
397
    const isNVue = !!config.page[pagePath].nvue;
398 399 400
    uniRoutes.push({
      path: '/' + pagePath,
      meta: {
fxy060608's avatar
fxy060608 已提交
401
        isQuit,
fxy060608's avatar
fxy060608 已提交
402 403 404 405
        isTabBar,
        isNVue
      },
      window: config.page[pagePath].window || {}
406 407 408
    });
  });
}
fxy060608's avatar
fxy060608 已提交
409

fxy060608's avatar
fxy060608 已提交
410 411 412
function registerConfig (config, {
  plus
}) {
413
  Object.assign(uniConfig, config);
fxy060608's avatar
fxy060608 已提交
414 415 416 417 418 419 420 421 422

  uniConfig.viewport = '';
  uniConfig.defaultFontSize = '';

  if (uniConfig.nvueCompiler === 'uni-app') {
    uniConfig.viewport = plus.screen.resolutionWidth;
    uniConfig.defaultFontSize = uniConfig.viewport / 20;
  }

423
  parseRoutes(uniConfig);
fxy060608's avatar
fxy060608 已提交
424 425 426 427

  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] registerConfig`, uniConfig);
  }
428 429
}

fxy060608's avatar
fxy060608 已提交
430 431 432
function initOn (on, {
  getApp,
  getCurrentPages
fxy060608's avatar
fxy060608 已提交
433
}) {
fxy060608's avatar
fxy060608 已提交
434 435 436
  function onError (err) {
    callAppHook(getApp(), 'onError', err);
  }
fxy060608's avatar
fxy060608 已提交
437

fxy060608's avatar
fxy060608 已提交
438 439
  function onPageNotFound (page) {
    callAppHook(getApp(), 'onPageNotFound', page);
fxy060608's avatar
fxy060608 已提交
440 441
  }

fxy060608's avatar
fxy060608 已提交
442 443 444 445
  function onPullDownRefresh (args, pageId) {
    const page = getCurrentPages().find(page => page.$page.id === pageId);
    if (page) {
      callPageHook(page, 'onPullDownRefresh');
fxy060608's avatar
fxy060608 已提交
446 447 448
    }
  }

fxy060608's avatar
fxy060608 已提交
449 450 451 452 453 454
  function callCurrentPageHook (hook, args) {
    const pages = getCurrentPages();
    if (pages.length) {
      callPageHook(pages[pages.length - 1], hook, args);
    }
  }
fxy060608's avatar
fxy060608 已提交
455

fxy060608's avatar
fxy060608 已提交
456 457 458 459
  function createCallCurrentPageHook (hook) {
    return function (args) {
      callCurrentPageHook(hook, args);
    }
fxy060608's avatar
fxy060608 已提交
460 461
  }

fxy060608's avatar
fxy060608 已提交
462 463 464
  function onAppEnterBackground () {
    callAppHook(getApp(), 'onHide');
    callCurrentPageHook('onHide');
fxy060608's avatar
fxy060608 已提交
465 466
  }

fxy060608's avatar
fxy060608 已提交
467 468 469
  function onAppEnterForeground () {
    callAppHook(getApp(), 'onShow');
    callCurrentPageHook('onShow');
fxy060608's avatar
fxy060608 已提交
470 471
  }

fxy060608's avatar
fxy060608 已提交
472 473 474 475 476 477 478 479
  function onWebInvokeAppService ({
    name,
    arg
  }, pageId) {
    if (name === 'postMessage') ; else {
      uni[name](arg);
    }
  }
fxy060608's avatar
fxy060608 已提交
480

fxy060608's avatar
fxy060608 已提交
481 482 483 484 485 486 487 488
  const routeHooks = {
    navigateTo () {
      callCurrentPageHook('onHide');
    },
    navigateBack () {
      callCurrentPageHook('onShow');
    }
  };
fxy060608's avatar
fxy060608 已提交
489

fxy060608's avatar
fxy060608 已提交
490 491 492 493 494
  function onAppRoute ({
    type
  }) {
    const routeHook = routeHooks[type];
    routeHook && routeHook();
fxy060608's avatar
fxy060608 已提交
495 496 497 498 499
  }

  on('onError', onError);
  on('onPageNotFound', onPageNotFound);

fxy060608's avatar
fxy060608 已提交
500 501 502 503
  { // 后续有时间,h5 平台也要迁移到 onAppRoute
    on('onAppRoute', onAppRoute);
  }

fxy060608's avatar
fxy060608 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  on('onAppEnterBackground', onAppEnterBackground);
  on('onAppEnterForeground', onAppEnterForeground);

  on('onPullDownRefresh', onPullDownRefresh);

  on('onTabItemTap', createCallCurrentPageHook('onTabItemTap'));
  on('onNavigationBarButtonTap', createCallCurrentPageHook('onNavigationBarButtonTap'));

  on('onNavigationBarSearchInputChanged', createCallCurrentPageHook('onNavigationBarSearchInputChanged'));
  on('onNavigationBarSearchInputConfirmed', createCallCurrentPageHook('onNavigationBarSearchInputConfirmed'));
  on('onNavigationBarSearchInputClicked', createCallCurrentPageHook('onNavigationBarSearchInputClicked'));

  on('onWebInvokeAppService', onWebInvokeAppService);
}

fxy060608's avatar
fxy060608 已提交
519 520
let bridge;

fxy060608's avatar
fxy060608 已提交
521
function initServiceJSBridge (Vue, instanceContext) {
fxy060608's avatar
fxy060608 已提交
522 523 524
  if (bridge) {
    return bridge
  }
fxy060608's avatar
fxy060608 已提交
525

fxy060608's avatar
fxy060608 已提交
526 527
  const Emitter = new Vue();

fxy060608's avatar
fxy060608 已提交
528
  bridge = {
fxy060608's avatar
fxy060608 已提交
529 530 531
    on: Emitter.$on.bind(Emitter),
    off: Emitter.$off.bind(Emitter),
    once: Emitter.$once.bind(Emitter),
fxy060608's avatar
fxy060608 已提交
532
    emit: Emitter.$emit.bind(Emitter)
fxy060608's avatar
fxy060608 已提交
533 534
  };

fxy060608's avatar
fxy060608 已提交
535
  initOn(bridge.on, instanceContext);
fxy060608's avatar
fxy060608 已提交
536 537 538 539

  return bridge
}

fxy060608's avatar
fxy060608 已提交
540 541
let uni$1;

fxy060608's avatar
fxy060608 已提交
542 543 544
function createInstanceContext (instanceContext) {
  const {
    weex,
fxy060608's avatar
fxy060608 已提交
545
    Vue,
fxy060608's avatar
fxy060608 已提交
546 547
    WeexPlus
  } = instanceContext;
fxy060608's avatar
fxy060608 已提交
548
  const plus = new WeexPlus(weex);
fxy060608's avatar
fxy060608 已提交
549

fxy060608's avatar
fxy060608 已提交
550
  const UniServiceJSBridge = initServiceJSBridge(Vue, {
fxy060608's avatar
fxy060608 已提交
551
    plus,
fxy060608's avatar
fxy060608 已提交
552
    getApp,
fxy060608's avatar
fxy060608 已提交
553
    getCurrentPages
fxy060608's avatar
fxy060608 已提交
554
  });
fxy060608's avatar
fxy060608 已提交
555

fxy060608's avatar
fxy060608 已提交
556 557 558 559
  function __registerPage (page) {
    return registerPage(page, instanceContext)
  }

fxy060608's avatar
fxy060608 已提交
560 561 562 563 564 565
  if (!uni$1) {
    uni$1 = createUniInstance(
      weex,
      plus,
      uniConfig,
      uniRoutes,
fxy060608's avatar
fxy060608 已提交
566
      __registerPage,
fxy060608's avatar
fxy060608 已提交
567 568 569 570 571 572
      UniServiceJSBridge,
      getApp,
      getCurrentPages
    );
  }

fxy060608's avatar
fxy060608 已提交
573
  return {
574 575 576
    __uniConfig: uniConfig,
    __uniRoutes: uniRoutes,
    __registerConfig (config) {
fxy060608's avatar
fxy060608 已提交
577
      return registerConfig(config, instanceContext)
578 579
    },
    __registerApp (appVm) {
fxy060608's avatar
fxy060608 已提交
580
      return registerApp(appVm, instanceContext)
581
    },
fxy060608's avatar
fxy060608 已提交
582
    __registerPage,
fxy060608's avatar
fxy060608 已提交
583
    plus,
fxy060608's avatar
fxy060608 已提交
584
    uni: uni$1,
fxy060608's avatar
fxy060608 已提交
585
    getApp,
fxy060608's avatar
fxy060608 已提交
586
    getCurrentPages,
fxy060608's avatar
fxy060608 已提交
587
    UniServiceJSBridge
fxy060608's avatar
fxy060608 已提交
588 589 590 591
  }
}

export { createInstanceContext };