router.js 6.47 KB
const _routeHooks = Symbol('_routeHooks')
const _query = Symbol('_query')
const _routerList = Symbol('_routerList')
import util from '../utils/util.js'
const generateRoutList = routerList => {
  let _routerList = routerList
  const tabBarList = __wxConfig?.tabBar?.list || []
  try {
    _routerList = routerList.map(item => {
      let obj = {}
      if (item.parent != '__plugin__') {
        obj = {
          ...item,
          isTab: tabBarList.some(({ pagePath }) => item.url.includes(pagePath.replace('.html', '')))
        }
        if (item.parent !== 'pages') {
          let parentList = item.url.split(`/`)
          if (parentList.length > 5) {
            item.url = item.url.replace(/\/__plugin__\/[a-z0-9A-Z]+/, '')
            obj.subPages = item.url.split(`/${item.parent}/pages/`)[1].split('/')[0]
          }
        }
      }
      return obj
    })
  } catch (err) {}
  return _routerList
}
class Router {
  [_query] = {};
  [_routeHooks] = [];
  [_routerList] = []
  constructor(router) {
    this[_routerList] = generateRoutList(router)
    wx.onAppRoute &&
      wx.onAppRoute(e => {
        let thisPage = this.getPageInstance()
        if (thisPage) {
          if (!wx.$version)
            util.getMockConfig().then(({ version }) => {
              wx.$version = version || '1.0.0'
              thisPage.setData({
                img_version: wx.$version
              })
            })
          else {
            thisPage.setData({
              img_version: wx.$version
            })
          }
          thisPage.setData({
            IMGURL: wx.$imgUrl
          })
          wx.hideHomeButton()
          this.setNavigationBarTitleText(thisPage)
          let onRoute = thisPage.onRoute
          thisPage.$query = this[_query]
          typeof onRoute === 'function' && onRoute(this[_query])
          let userInfo = util.getUserInfo()
          if (userInfo && userInfo.phone) {
            if (wx.$authStatus) {
              thisPage.setData({
                userInfo: null
              })
            } else {
              thisPage.setData({
                userInfo
              })
              if (thisPage.init) thisPage.init(userInfo)
            }
          }
        }
        this[_routeHooks].forEach(fn => {
          try {
            typeof fn === 'function' && fn(e, this[_query], this[_routerList])
          } catch (err) {
            console.log(err)
          }
        })
        this[_query] = {}
      })
  }
  /**设置标题栏 */
  setNavigationBarTitleText(thisPage) {
    let title = wx.$util.getNavigationBarTitleText()
    if (wx.$util.getUserInfo()) title = wx.$util.getUserInfo().merchantName
    const router = `${thisPage.__route__}.html`
    if (__wxConfig && __wxConfig.page && __wxConfig.page[router]) {
      let { navigationBarTitleText, navigationStyle } = __wxConfig.page[router].window
      if (!title) title = ''
      if (!navigationBarTitleText && !navigationStyle)
        wx.setNavigationBarTitle({
          title
        })
    }
  }
  /**获取页面对象实例 */
  getPageInstance = (size = 1) => {
    const pages = getCurrentPages()
    return pages[pages.length - size]
  }
  checkRouter(route, events) {
    this[_query] = events || {}
    const [_parent, _name, last_name] = route.split('.')
    let name = route
    let [parent] = this.getPageInstance().__route__.split('/')
    let query = ''
    if (route.includes('?')) {
      let [_name_, _query_] = route.split('?')
      query = `?${_query_}`
      name = _name_
    }
    if (_parent && _name) {
      name = _name.split('?')[0]
      parent = _parent
    }
    /**只传页面名 默认跳转当前包下的页面,相同名称默认第一个 */
    if (!_name && !last_name) name = _parent
    const routerMapItem = this[_routerList].find(item => {
      if (route.includes('/')) return item.url === route
      else {
        if (last_name) {
          return item.parent === parent && item.name === last_name && item.subPages === name
        } else {
          return item.parent === parent && item.name === name
        }
      }
    })
    if (!routerMapItem) {
      console.error('找不到路由')
      return
    }
    return {
      routerMapItem,
      query
    }
  }
  /**跳转至H5 */
  jumpH5(url) {
    wx.navigateTo({
      url: `/pages/webView/webView?url=${encodeURIComponent(url)}`
    })
  }
  /**页面跳转
   *
   */
  jump(e) {
    const item = e.currentTarget.dataset
    this.go(item.url, item)
  }
  /**
   * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 ||
   * 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 $router.back() 可以返回到原页面。小程序中页面栈最多十层
   */
  go(route, events) {
    let { routerMapItem, query } = this.checkRouter(route, events)
    if (routerMapItem.isTab) {
      wx.switchTab({
        url: routerMapItem.url
      })
    } else {
      wx.navigateTo({
        url: `${routerMapItem.url}${query}`,
        success: res => events && res.eventChannel.emit('getData', events)
      })
    }
  }
  /**关闭所有页面,打开到应用内的某个页面 */
  reLaunch(route, events) {
    let { routerMapItem, query } = this.checkRouter(route, events)
    wx.reLaunch({
      url: `${routerMapItem.url}${query}`
    })
  }
  /**关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */
  redirectTo(route, events) {
    let { routerMapItem, query } = this.checkRouter(route, events)
    wx.redirectTo({
      url: `${routerMapItem.url}${query}`
    })
  }
  /**prevPageSize = 1
   * 返回上prevPageSize页
   * callBack返回上prevPageSize页对象  */
  back(callBack, prevPageSize = 1) {
    let prevPage = this.getPageInstance(Number(prevPageSize) + 1)
    if (callBack && 'function' === typeof callBack) callBack(prevPage)
    wx.navigateBack({
      delta: prevPageSize
    }).catch(err => {
      this.goHome()
    })
  }
  goHome() {
    let [index] = this[_routerList]
    wx.switchTab({
      url: index.url
    })
  }
  /**获取上一个页面传的数据 */
  getData(callBack) {
    const data = this.getPageInstance().getOpenerEventChannel()
    if (Object.keys(data).length !== 0) data.on('getData', res => callBack(res))
  }
  onRoute(fn) {
    this[_routeHooks].push(fn)
    return () => {
      const i = list.indexOf(fn)
      if (i > -1) list.splice(i, 1)
    }
  }
  async intercept() {
    const isAuth = !!wx.$authStatus
    this.getPageInstance().setData({
      showLogin: isAuth
    })
    return isAuth
  }
}

export default Router