Files
www/store/index.ts
T
2021-10-24 23:49:09 +07:00

156 lines
3.2 KiB
TypeScript

import { actionTree, getAccessorType, mutationTree } from 'typed-vuex'
import { api } from '~/assets/api'
import { jsonClone } from '~/assets/util'
const TAB_SETTINGS = 'TABS_SETTINGS'
interface ISettings {
level: number | null
levelMin: number | null
}
interface ITab {
title: string
component: string
permanent?: boolean
query: Record<string, string>
}
export const state = () => ({
settings: {
level: null,
levelMin: null,
sentenceMin: null,
sentenceMax: null,
} as ISettings,
isApp: false,
tabs: [] as ITab[],
activeTab: 0,
identifier: '',
})
export const mutations = mutationTree(state, {
SET_SETTINGS(state, settings: ISettings) {
state.settings = settings
},
SET_IS_APP(state, isApp: boolean) {
state.isApp = isApp
},
SET_ALL_TABS(
state,
o: {
tabs: ITab[]
activeTab: number
} = state
) {
localStorage.setItem(
TAB_SETTINGS,
JSON.stringify({
tabs: o.tabs,
activeTabs: o.activeTab,
})
)
state.tabs = jsonClone(o.tabs)
state.activeTab = jsonClone(o.activeTab)
},
SET_TAB_TITLE(state, { i, title }: { i: number; title: string }) {
state.tabs[i].title = title
this.SET_ALL_TABS(state)
},
ADD_TAB(
state,
{
component,
query = {},
first,
}: {
component: string
query?: Record<string, string>
first?: boolean
}
) {
if (first) {
state.tabs = [
{
title: component,
component,
permanent: true,
query,
},
]
} else {
state.tabs = [
...state.tabs,
{
title: component,
component,
query,
},
]
}
state.activeTab = state.tabs.length - 1
this.SET_ALL_TABS(state)
},
DELETE_TAB(state, { i }: { i: number }) {
state.tabs.splice(i, 1)
if (state.activeTab >= state.tabs.length) {
state.activeTab = state.tabs.length - 1
}
this.SET_ALL_TABS(state)
},
SET_TAB_COMPONENT(state, { i, component }: { i: number; component: string }) {
state.tabs[i].component = component
this.SET_ALL_TABS(state)
},
SET_TAB_CURRENT(state, { i }: { i: number }) {
state.activeTab = i
this.SET_ALL_TABS(state)
},
SET_IDENTIFIER(state, name: string) {
state.identifier = name
},
})
export const actions = actionTree(
{ state, mutations },
{
async nuxtServerInit({ dispatch, commit }) {
await dispatch('updateSetings')
const settings = localStorage.getItem(TAB_SETTINGS)
if (settings) commit('SET_ALL_TABS', JSON.parse(settings))
},
async updateSettings({ commit }) {
const r = await api.user_getSettings({
select: ['identifier', 'levelMin', 'level'],
})
commit('SET_IS_APP', !!r)
commit('SET_IDENTIFIER', r?.identifier || '')
if (r) {
if (!r.levelMin) {
r.levelMin = 1
await api.user_updateSettings({
levelMin: r.levelMin,
})
}
}
commit('SET_SETTINGS', {
level: r?.level || null,
levelMin: r?.levelMin || null,
})
},
}
)
export const accessorType = getAccessorType({
state,
mutations,
actions,
})