-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
note.ts
67 lines (58 loc) · 1.62 KB
/
note.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
import { MaybeRef, useFetch } from '@vueuse/core'
import { computed, ref, Ref, unref } from 'vue'
import type { SlideInfo, SlideInfoExtended } from '@slidev/types'
export interface UseSlideInfo{
info: Ref<SlideInfoExtended | undefined>
update: (data: Partial<SlideInfo>) => Promise<SlideInfoExtended | void>
}
export function useSlideInfo(id: number | undefined): UseSlideInfo {
if (id == null) {
return {
info: ref() as Ref<SlideInfoExtended | undefined>,
update: async() => {},
}
}
const url = `/@slidev/slide/${id}.json`
const { data: info, execute } = useFetch(url).json().get()
execute()
const update = async(data: Partial<SlideInfo>) => {
return await fetch(
url,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
},
).then(r => r.json())
}
import.meta.hot?.on('slidev-update', (payload) => {
if (payload.id === id)
info.value = payload.data
})
return {
info,
update,
}
}
const map: Record<string, UseSlideInfo> = {}
export function useDynamicSlideInfo(id: MaybeRef<number | undefined>) {
function get(id: number | undefined) {
const i = `${id}`
if (!map[i])
map[i] = useSlideInfo(id)
return map[i]
}
return {
info: computed(() => get(unref(id)).info.value),
update: async(data: Partial<SlideInfo>, newId?: number) => {
const info = get(newId ?? unref(id))
const newData = await info.update(data)
if (newData)
info.info.value = newData
return newData
},
}
}