forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.ts
More file actions
49 lines (41 loc) · 1.61 KB
/
context.ts
File metadata and controls
49 lines (41 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { MediaSize, useMediaSize, useProvide, useProvider, useRequest } from "@hooks"
import cateService from "@service/cate-service"
import { toMap } from '@util/array'
import { CATE_NOT_SET_ID } from '@util/site'
import { computed, reactive, watch, type Ref } from "vue"
import { t } from './locale'
type MenuLayout = 'nav' | 'sidebar'
interface CategoryInstance {
enabled: boolean
all: timer.site.Cate[]
nameMap: Record<number, string>
refresh(): void
}
type AppContextValue = {
category: Readonly<CategoryInstance>
layout: Readonly<Ref<MenuLayout>>
}
const NAMESPACE = '_'
export const initAppContext = () => {
const { refresh: refreshCategories } = useRequest(() => cateService.listAll(), {
onSuccess: categories => {
category.all = categories
const map = toMap(categories, c => c.id, c => c.name)
map[CATE_NOT_SET_ID] = t(msg => msg.shared.cate.notSet)
category.nameMap = map
}
})
const mediaSize = useMediaSize()
const layout = computed<MenuLayout>(() => mediaSize.value > MediaSize.sm ? 'sidebar' : 'nav')
watch(layout, v => category.enabled = v === 'sidebar')
const category: CategoryInstance = reactive({
enabled: layout.value === 'sidebar',
all: [],
nameMap: {},
refresh: refreshCategories,
})
useProvide<AppContextValue>(NAMESPACE, { category, layout })
return { layout }
}
export const useCategory = () => useProvider<AppContextValue, "category">(NAMESPACE, "category").category
export const useLayout = () => useProvider<AppContextValue, "layout">(NAMESPACE, "layout").layout