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
68 lines (54 loc) · 2.32 KB
/
context.ts
File metadata and controls
68 lines (54 loc) · 2.32 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Copyright (c) 2024 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { useLocalStorage, useProvide, useProvider, useRequest } from "@hooks"
import statService from "@service/stat-service"
import { ref, watch, type Ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import type { AnalysisTarget } from "./types"
type Context = {
target: Ref<AnalysisTarget | undefined>
timeFormat: Ref<timer.app.TimeFormat>
rows: Ref<timer.stat.Row[]>
}
export type AnalysisQuery = Partial<timer.site.SiteKey> & {
cateId?: string
}
function parseQuery(): AnalysisTarget | undefined {
// Process the query param
const query = useRoute().query as unknown as AnalysisQuery
useRouter().replace({ query: {} })
const { host, type: siteType, cateId } = query
if (cateId) return { type: 'cate', key: parseInt(cateId) }
if (host && siteType) return { type: 'site', key: { host, type: siteType } }
return undefined
}
async function queryRows(target: AnalysisTarget | undefined): Promise<(timer.stat.CateRow | timer.stat.SiteRow)[]> {
const { key, type } = target ?? {}
if (!key) return []
if (type === 'cate') {
return statService.selectCate({ cateIds: [key], sortKey: 'date' })
} else if (type === 'site') {
const { host, type: siteType } = key ?? {}
return statService.selectSite({ host, mergeHost: siteType === 'merged', sortKey: 'date' })
} else {
// Not supported yet
return []
}
}
const NAMESPACE = 'siteAnalysis'
export const initAnalysis = () => {
const target = ref(parseQuery())
const [cachedFormat, setFormatCache] = useLocalStorage<timer.app.TimeFormat>('analysis_timeFormat')
const timeFormat = ref(cachedFormat ?? 'default')
watch(timeFormat, setFormatCache)
const { data: rows, loading } = useRequest(() => queryRows(target.value), { deps: target, defaultValue: [] })
useProvide<Context>(NAMESPACE, { target, timeFormat, rows })
return { loading }
}
export const useAnalysisTarget = () => useProvider<Context, 'target'>(NAMESPACE, "target").target
export const useAnalysisTimeFormat = () => useProvider<Context, 'timeFormat'>(NAMESPACE, "timeFormat").timeFormat
export const useAnalysisRows = () => useProvider<Context, 'rows'>(NAMESPACE, "rows").rows