117 lines
2.9 KiB
TypeScript
117 lines
2.9 KiB
TypeScript
import type { CustomTabBarItem, CustomTabBarItemBadge } from './types'
|
|
import { reactive } from 'vue'
|
|
|
|
import {
|
|
tabbarList as _tabbarList,
|
|
customTabbarEnable,
|
|
selectedTabbarStrategy,
|
|
TABBAR_STRATEGY_MAP,
|
|
getTabbarListByClientType,
|
|
type ClientTypeKey,
|
|
} from './config'
|
|
|
|
// 中间的鼓包tabbarItem的开关
|
|
const BULGE_ENABLE = false
|
|
|
|
/** tabbarList 动态列表,根据客户端类型切换 */
|
|
const tabbarList = reactive<CustomTabBarItem[]>(_tabbarList.map(item => ({
|
|
...item,
|
|
pagePath: item.pagePath.startsWith('/') ? item.pagePath : `/${item.pagePath}`,
|
|
})))
|
|
|
|
// 初始化鼓包
|
|
function initBulge() {
|
|
if (customTabbarEnable && BULGE_ENABLE) {
|
|
if (tabbarList.length % 2) {
|
|
console.error('有鼓包时 tabbar 数量必须是偶数')
|
|
}
|
|
const hasBulge = tabbarList.some(item => item.isBulge)
|
|
if (!hasBulge) {
|
|
tabbarList.splice(tabbarList.length / 2, 0, {
|
|
isBulge: true,
|
|
} as CustomTabBarItem)
|
|
}
|
|
}
|
|
}
|
|
initBulge()
|
|
|
|
export function isPageTabbar(path: string) {
|
|
if (selectedTabbarStrategy === TABBAR_STRATEGY_MAP.NO_TABBAR) {
|
|
return false
|
|
}
|
|
const _path = path.split('?')[0]
|
|
return tabbarList.some(item => item.pagePath === _path)
|
|
}
|
|
|
|
/**
|
|
* 自定义 tabbar 的状态管理
|
|
*/
|
|
const tabbarStore = reactive({
|
|
curIdx: uni.getStorageSync('app-tabbar-index') || 0,
|
|
prevIdx: uni.getStorageSync('app-tabbar-index') || 0,
|
|
|
|
setCurIdx(idx: number) {
|
|
this.curIdx = idx
|
|
uni.setStorageSync('app-tabbar-index', idx)
|
|
},
|
|
|
|
setTabbarItemBadge(idx: number, badge: CustomTabBarItemBadge) {
|
|
if (tabbarList[idx]) {
|
|
tabbarList[idx].badge = badge
|
|
}
|
|
},
|
|
|
|
/**
|
|
* 根据客户端类型切换 tabbar 列表
|
|
*/
|
|
setTabbarByClientType(clientType: ClientTypeKey) {
|
|
const newList = getTabbarListByClientType(clientType)
|
|
|
|
// 清空现有列表
|
|
tabbarList.length = 0
|
|
|
|
// 填充新列表
|
|
newList.forEach(item => {
|
|
tabbarList.push({
|
|
...item,
|
|
pagePath: (item.pagePath.startsWith('/') ? item.pagePath : `/${item.pagePath}`) as any,
|
|
})
|
|
})
|
|
|
|
// 重新初始化鼓包
|
|
initBulge()
|
|
|
|
// 重置当前索引
|
|
this.setCurIdx(0)
|
|
},
|
|
|
|
setAutoCurIdx(path: string) {
|
|
if (path === '/') {
|
|
this.setCurIdx(0)
|
|
return
|
|
}
|
|
const index = tabbarList.findIndex(item => item.pagePath === path)
|
|
if (index === -1) {
|
|
const pagesPathList = getCurrentPages().map(item => item.route.startsWith('/') ? item.route : `/${item.route}`)
|
|
const flag = tabbarList.some(item => pagesPathList.includes(item.pagePath))
|
|
if (!flag) {
|
|
this.setCurIdx(0)
|
|
return
|
|
}
|
|
}
|
|
else {
|
|
this.setCurIdx(index)
|
|
}
|
|
},
|
|
|
|
restorePrevIdx() {
|
|
if (this.prevIdx === this.curIdx)
|
|
return
|
|
this.setCurIdx(this.prevIdx)
|
|
this.prevIdx = uni.getStorageSync('app-tabbar-index') || 0
|
|
},
|
|
})
|
|
|
|
export { tabbarList, tabbarStore }
|
|
|