-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
data.ts
83 lines (76 loc) · 1.89 KB
/
data.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
InjectionKey,
Ref,
computed,
inject,
readonly,
ref,
shallowRef
} from 'vue'
import { Route } from './router.js'
import siteData from '@siteData'
import {
PageData,
SiteData,
resolveSiteDataByRoute,
createTitle
} from '../shared.js'
import { withBase } from './utils.js'
export const dataSymbol: InjectionKey<VitePressData> = Symbol()
export interface VitePressData<T = any> {
site: Ref<SiteData<T>>
page: Ref<PageData>
theme: Ref<T>
frontmatter: Ref<PageData['frontmatter']>
title: Ref<string>
description: Ref<string>
lang: Ref<string>
localePath: Ref<string>
isDark: Ref<boolean>
}
// site data is a singleton
export const siteDataRef: Ref<SiteData> = shallowRef(
(import.meta.env.PROD ? siteData : readonly(siteData)) as SiteData
)
// hmr
if (import.meta.hot) {
import.meta.hot.accept('/@siteData', (m) => {
if (m) {
siteDataRef.value = m.default
}
})
}
// per-app data
export function initData(route: Route): VitePressData {
const site = computed(() =>
resolveSiteDataByRoute(siteDataRef.value, route.path)
)
return {
site,
theme: computed(() => site.value.themeConfig),
page: computed(() => route.data),
frontmatter: computed(() => route.data.frontmatter),
lang: computed(() => site.value.lang),
localePath: computed(() => {
const { langs, lang } = site.value
const path = Object.keys(langs).find(
(langPath) => langs[langPath].lang === lang
)
return withBase(path || '/')
}),
title: computed(() => {
return createTitle(site.value, route.data)
}),
description: computed(() => {
return route.data.description || site.value.description
}),
isDark: ref(false)
}
}
export function useData<T = any>(): VitePressData<T> {
const data = inject(dataSymbol)
if (!data) {
throw new Error('vitepress data not properly injected in app')
}
return data
}