import { hooks } from '@opentiny/vue-common'
import { $local } from './useStorage'
const defaultPath = {
pc: '/pc/button/base',
mobile: '/mobile/navbar/left-right-arrow',
'mobile-first': '/mobile-first/calendar-bar/basic-usage'
}
const modeNames = Object.keys(defaultPath)
const parsePath = (path) => {
const items = path.split('/')
state.mode = items[1]
state.pathName = items[2]
}
const state = hooks.reactive({
mode: '',
pathName: '',
demoId: '',
modeCtx: $local.modeCtx || defaultPath
})
const fn = {
loadPage: () => {
const urlSegments = location.pathname.split('/')
let mode = urlSegments[1]
if (modeNames.includes(mode)) {
parsePath(location.pathname)
state.demoId = location.hash.slice(1)
fn.cacheCtx()
} else {
fn.changeMode('pc')
fn.pushToUrl()
}
},
changeMode: (mode) => {
parsePath(state.modeCtx[mode])
},
cacheCtx: () => {
state.modeCtx[state.mode] = `/${state.mode}/${state.pathName}#${state.demoId}`
$local.modeCtx = state.modeCtx
},
pushToUrl: () => history.pushState({}, '', state.modeCtx[state.mode])
}
export function useModeCtx() {
return {
state,
fn
}
}