init-client.js 2.83 KB
import Vue from 'vue';
import cookie from 'yoho-cookie';
import yoho from 'common/yoho';
import version from 'utils/version';

const setStatusBar = (width, height, store) => {
  const statusBar = {
    statusBarStatus: false,
    statusBarHeight: 0
  };

  // 仅支持ios
  if (yoho.isYohoBuy && yoho.isiOS) {
    let isX = (height / width) > 2.1;
    let actionBarHeight = isX ? 32 : 0;

    statusBar.statusBarHeight = isX ? 44 : 22;

    if (store) {
      store.commit('SET_STATUS_BAR_HEIGHT', {
        height: statusBar.statusBarHeight
      });
      store.commit('SET_ACTION_BAR_HEIGHT', {
        height: actionBarHeight
      });
    }

    function getAppVersion(str, split) {
        const match = str.match(new RegExp('(^|)app_version=([^' + split + ']*)(' + split + '|$)'));

        return match && match.length ? match[2] : '';
    }

    const appVersion = getAppVersion(document.cookie, ';') || getAppVersion(location.href, '&');

    if (version(appVersion, '6.9.2') >= 0) {
      statusBar.statusBarStatus = true;
      store && store.commit('SET_STATUS_BAR_STATUS', {status: true});
    }
  }

  return statusBar;
};

const initClient = (store) => {
  window.onresize = () => {
    const {clientWidth, clientHeight} = document.body;
    store.commit('SET_WINDOW_SIZE', {clientWidth, clientHeight});
    setStatusBar(clientWidth, clientHeight, store);
  };
  const {clientWidth, clientHeight} = document.body;

  store.commit('SET_WINDOW_SIZE', {clientWidth, clientHeight});
  let supportsPassive = false;

  try {
    const opts = Object.defineProperty({}, 'passive', {
      get() {
        supportsPassive = true;
        return true;
      }
    });

    window.addEventListener('test', null, opts);
  } catch (e) {} //eslint-disable-line
  store.commit('SET_SUPPORT_PASSIVE', {supportsPassive});

  setStatusBar(clientWidth, clientHeight, store);

  if (/yoho/i.test(navigator.userAgent) && /supportWebp/i.test(navigator.userAgent)) {
    store.commit('SET_SUPPORT_WEBP', {supportWebp: true});
  }
  let img = new Image();

  img.onload = () => {
    if (img.width > 0 && img.height > 0) {
      store.commit('SET_SUPPORT_WEBP', {supportWebp: true});
    }
  };
  img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';

  Vue.$sdk.getUser().then(user => {
    if (user && user.uid) {
      store.commit('SET_LOGIN_INFO', user);
    }
  });

  Vue.$yoho.ready(() => {
    Vue.$yoho.setWebview({
      bounces: false,
      clearCacheWhenDestroy: false
    });
  });
};

const getYohoState = () => {
  const {clientWidth, clientHeight} = document.body;

  return {
    context: {
      env: {
        isApp: yoho.isApp,
        isiOS: yoho.isiOS,
        isAndroid: yoho.isAndroid,
        isYohoBuy: yoho.isYohoBuy
      }
    },
    window: setStatusBar(clientWidth, clientHeight)
  }
};

export {
  initClient,
  getYohoState
};