1+ import { type I18nKey , t } from '@app/locale'
2+ import { createStringUnionGuard } from 'typescript-guard'
3+ import { computed , type ShallowRef } from 'vue'
4+ import { type LocationQuery , useRoute , useRouter } from 'vue-router'
5+
6+ export type IntegrationCategory = 'backup' | 'notification'
7+ const isCategory = createStringUnionGuard < IntegrationCategory > ( 'backup' , 'notification' )
8+
9+ const CATE_LABELS : Record < IntegrationCategory , I18nKey > = {
10+ backup : msg => msg . option . backup . title ,
11+ notification : msg => msg . integration . notification . title ,
12+ }
13+
14+ const PARAM = "i"
15+
16+ function parseInit ( query : LocationQuery ) : IntegrationCategory | undefined {
17+ const initialQuery = query [ PARAM ]
18+ const queryVal = Array . isArray ( initialQuery ) ? initialQuery [ 0 ] : initialQuery
19+ return isCategory ( queryVal ) ? queryVal : undefined
20+ }
21+
22+ export const useCategory = ( ) : {
23+ category : ShallowRef < IntegrationCategory >
24+ setCategory : ( value : unknown ) => void
25+ getLabel : ( value : unknown ) => string | undefined
26+ } => {
27+ const route = useRoute ( )
28+ const router = useRouter ( )
29+
30+ const category = computed ( {
31+ set ( value : IntegrationCategory ) {
32+ const oldQuery = route . query
33+ const query : LocationQuery = {
34+ ...oldQuery ,
35+ [ PARAM ] : value ,
36+ }
37+ router . replace ( { query } )
38+ } ,
39+ get : ( ) => parseInit ( route . query ) ?? 'backup' ,
40+ } )
41+
42+ const setCategory = ( value : unknown ) => isCategory ( value ) && ( category . value = value )
43+ const getLabel = ( value : unknown ) => {
44+ const key = isCategory ( value ) ? CATE_LABELS [ value ] : undefined
45+ return key ? t ( key ) : undefined
46+ }
47+
48+ return { category, setCategory, getLabel }
49+ }
0 commit comments