docs/.vitepress/theme/composables/useBookmarks.ts
64 lines · 1592 bytes
1import { ref, watch } from 'vue'
2
3export interface Bookmark {
4 title: string
5 anchor: string
6 path: string
7}
8
9const STORAGE_KEY = 'wotaku-bookmarks'
10export const BOOKMARK_CHANGE_EVENT = 'wotaku-bookmarks-changed'
11
12const bookmarks = ref<Bookmark[]>([])
13let initialized = false
14
15function loadFromStorage(): Bookmark[] {
16 try {
17 return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]')
18 } catch {
19 return []
20 }
21}
22
23function saveToStorage(): void {
24 localStorage.setItem(STORAGE_KEY, JSON.stringify(bookmarks.value))
25}
26
27if (typeof window !== 'undefined') {
28 watch(bookmarks, () => {
29 window.dispatchEvent(new CustomEvent(BOOKMARK_CHANGE_EVENT))
30 }, { deep: true, flush: 'post' })
31}
32
33export function useBookmarks() {
34 if (!initialized && typeof window !== 'undefined') {
35 initialized = true
36 bookmarks.value = loadFromStorage()
37 }
38
39 function isBookmarked(anchor: string, path: string): boolean {
40 return bookmarks.value.some(b => b.anchor === anchor && b.path === path)
41 }
42
43 function toggle(bookmark: Bookmark): void {
44 const idx = bookmarks.value.findIndex(
45 b => b.anchor === bookmark.anchor && b.path === bookmark.path
46 )
47 if (idx >= 0) {
48 bookmarks.value.splice(idx, 1)
49 } else {
50 bookmarks.value.push(bookmark)
51 }
52 saveToStorage()
53 }
54
55 function remove(anchor: string, path: string): void {
56 const idx = bookmarks.value.findIndex(b => b.anchor === anchor && b.path === path)
57 if (idx >= 0) {
58 bookmarks.value.splice(idx, 1)
59 saveToStorage()
60 }
61 }
62
63 return { bookmarks, isBookmarked, toggle, remove }
64}