docs/.vitepress/theme/components/BookmarksPanel.vue

dc37a0812a9971107e75ecfdb141c3d5bf0289fc
wotaku/docs/.vitepress/theme/components/BookmarksPanel.vue history · blame · raw

581 lines · 16557 bytes

  1<script setup lang="ts">
  2import { onClickOutside, useEventListener } from '@vueuse/core'
  3import { ArrowLeft, Bookmark, Hash } from 'lucide-vue-next'
  4import { inBrowser } from 'vitepress'
  5import type { DefaultTheme } from 'vitepress/theme'
  6import { computed, nextTick, ref, watch } from 'vue'
  7import type { HomeCard } from '../../configs/constants'
  8import { homeCards, sidebar } from '../../configs/constants'
  9import type { Bookmark as BookmarkItem } from '../composables/useBookmarks'
 10import { useBookmarks } from '../composables/useBookmarks'
 11
 12const ICON_SIZE = 18
 13const ICON_STROKE = 2
 14
 15const { bookmarks, remove } = useBookmarks()
 16const isOpen = ref(false)
 17const wrapperRef = ref<HTMLElement>()
 18const buttonRef = ref<HTMLElement>()
 19const panelRef = ref<HTMLElement>()
 20const scrollRef = ref<HTMLElement>()
 21const showFade = ref(true)
 22const panelStyle = ref<Record<string, string>>({})
 23
 24onClickOutside(wrapperRef, () => {
 25  isOpen.value = false
 26})
 27
 28function onScroll() {
 29  if (!scrollRef.value) return
 30  const { scrollTop, scrollHeight, clientHeight } = scrollRef.value
 31  showFade.value = scrollTop + clientHeight < scrollHeight - 4
 32}
 33
 34function updatePanelPosition() {
 35  const wrapper = wrapperRef.value
 36  const button = buttonRef.value
 37  const panel = panelRef.value
 38  if (!wrapper || !button || !panel) return
 39
 40  if (!inBrowser || window.innerWidth <= 767) {
 41    panelStyle.value = {}
 42    return
 43  }
 44
 45  const viewportMargin = 12
 46  const wrapperRect = wrapper.getBoundingClientRect()
 47  const buttonRect = button.getBoundingClientRect()
 48  const panelWidth = panel.offsetWidth
 49  const centeredLeft = buttonRect.left + buttonRect.width / 2 - panelWidth / 2
 50  const maxLeft = Math.max(
 51    viewportMargin,
 52    window.innerWidth - viewportMargin - panelWidth
 53  )
 54  const viewportLeft = Math.min(Math.max(centeredLeft, viewportMargin), maxLeft)
 55
 56  panelStyle.value = {
 57    '--bookmarks-panel-left': `${viewportLeft - wrapperRect.left}px`,
 58    '--bookmarks-panel-shift': '0px'
 59  }
 60}
 61
 62watch(isOpen, async (open) => {
 63  if (!open) return
 64  await nextTick()
 65  updatePanelPosition()
 66  onScroll()
 67})
 68
 69useEventListener(inBrowser ? window : undefined, 'resize', () => {
 70  if (isOpen.value) updatePanelPosition()
 71})
 72
 73function flattenSidebarPaths(items: DefaultTheme.SidebarItem[]): string[] {
 74  const paths: string[] = []
 75  for (const item of items) {
 76    if (item.link) paths.push(item.link)
 77    if (item.items) paths.push(...flattenSidebarPaths(item.items))
 78  }
 79  return paths
 80}
 81
 82const sidebarPathOrder = flattenSidebarPaths(Array.isArray(sidebar) ? sidebar : Object.values(sidebar).flat())
 83
 84function sidebarIndex(path: string): number {
 85  const exact = sidebarPathOrder.indexOf(path)
 86  return exact !== -1 ? exact : Infinity
 87}
 88
 89function cardIconToClass(icon: string): string {
 90  const m = icon.match(/^:(.+):$/)
 91  if (!m) return 'i-lucide:file-text'
 92  const name = m[1]
 93  const dash = name.indexOf('-')
 94  if (dash === -1) return 'i-lucide:file-text'
 95  return `i-${name.slice(0, dash)}:${name.slice(dash + 1)}`
 96}
 97
 98function getPageCard(path: string): HomeCard | null {
 99  let best: HomeCard | null = null
100  let bestLen = 0
101  for (const card of homeCards) {
102    if ((path === card.link || path.startsWith(card.link + '/')) && card.link.length > bestLen) {
103      best = card
104      bestLen = card.link.length
105    }
106  }
107  return best
108}
109
110type PageGroup = { path: string; card: HomeCard | null; items: BookmarkItem[] }
111type TopLevelEntry = { type: 'page'; path: string; card: HomeCard | null; items: BookmarkItem[] }
112type FolderEntry = { type: 'folder'; section: string; parentCard: HomeCard | null; pages: PageGroup[] }
113type GroupEntry = TopLevelEntry | FolderEntry
114
115const grouped = computed((): GroupEntry[] => {
116  // Collect bookmarks by path
117  const byPath = new Map<string, BookmarkItem[]>()
118  for (const bm of bookmarks.value) {
119    if (!byPath.has(bm.path)) byPath.set(bm.path, [])
120    byPath.get(bm.path)!.push(bm)
121  }
122
123  // Separate into top-level pages and folder sub-pages (those with a section field)
124  const topPages: string[] = []
125  const folderMap = new Map<string, string[]>() // section → paths
126
127  for (const path of byPath.keys()) {
128    const card = getPageCard(path)
129    if (card?.section) {
130      if (!folderMap.has(card.section)) folderMap.set(card.section, [])
131      folderMap.get(card.section)!.push(path)
132    } else {
133      topPages.push(path)
134    }
135  }
136
137  // Sort top-level pages by exact sidebar position
138  topPages.sort((a, b) => sidebarIndex(a) - sidebarIndex(b))
139
140  // Build folder entries, sorted by parent card's sidebar position
141  const folderEntries: FolderEntry[] = [...folderMap.entries()]
142    .map(([section, paths]) => {
143      const parentCard = homeCards.find(c => c.title === section && !c.section) ?? null
144      const sortedPages = [...paths]
145        .sort((a, b) => sidebarIndex(a) - sidebarIndex(b))
146        .map(path => ({ path, card: getPageCard(path), items: byPath.get(path)! }))
147      return { type: 'folder' as const, section, parentCard, pages: sortedPages }
148    })
149    .sort((a, b) => sidebarIndex(a.parentCard?.link ?? '') - sidebarIndex(b.parentCard?.link ?? ''))
150
151  // Merge top-level and folder entries in sidebar order
152  const topEntries: TopLevelEntry[] = topPages.map(path => ({
153    type: 'page' as const,
154    path,
155    card: getPageCard(path),
156    items: byPath.get(path)!
157  }))
158
159  return [...topEntries, ...folderEntries].sort((a, b) => {
160    const ai = a.type === 'page' ? sidebarIndex(a.path) : sidebarIndex(a.parentCard?.link ?? '')
161    const bi = b.type === 'page' ? sidebarIndex(b.path) : sidebarIndex(b.parentCard?.link ?? '')
162    return ai - bi
163  })
164})
165</script>
166
167<template>
168  <div ref="wrapperRef" class="bookmarks-wrapper">
169    <button
170      ref="buttonRef"
171      type="button"
172      class="bookmarks-btn"
173      aria-label="Bookmarks"
174      :aria-expanded="isOpen"
175      @click="isOpen = !isOpen"
176    >
177      <Bookmark :size="ICON_SIZE" :stroke-width="ICON_STROKE" />
178    </button>
179
180    <Transition name="bookmarks-panel">
181      <div v-if="isOpen" ref="panelRef" class="bookmarks-panel" :style="panelStyle" role="dialog" aria-label="Bookmarks">
182        <div class="bookmarks-mobile-header">
183          <button type="button" class="bookmarks-mobile-back" aria-label="Back" @click="isOpen = false">
184            <ArrowLeft :size="18" :stroke-width="2" />
185          </button>
186          <span class="bookmarks-mobile-title">Bookmarks</span>
187        </div>
188        <div
189          ref="scrollRef"
190          class="bookmarks-scroll"
191          @scroll.passive="onScroll"
192        >
193          <div v-if="bookmarks.length === 0" class="bookmarks-empty">
194            <span class="bookmarks-empty-kaomoji">(˶ᵔ ᵕ ᵔ˶)</span>
195            <p class="bookmarks-empty-hint bookmarks-empty-hint--desktop">Tip: Hover over any primary heading under <strong>On this page</strong> and click <Bookmark :size="13" :stroke-width="2" class="bookmarks-empty-inline-icon" /> to bookmark it.</p>
196            <p class="bookmarks-empty-hint bookmarks-empty-hint--mobile">Tip: Tap <strong>On this page</strong> and press <Bookmark :size="13" :stroke-width="2" class="bookmarks-empty-inline-icon" /> next to any primary heading to bookmark it.</p>
197          </div>
198          <div v-else class="bookmarks-groups">
199            <template v-for="group in grouped" :key="group.type === 'page' ? group.path : group.section">
200
201              <!-- Top-level page (no folder) -->
202              <div v-if="group.type === 'page'" class="bookmarks-group">
203                <h3 class="bookmarks-group-title">
204                  <span v-if="group.card" :class="cardIconToClass(group.card.icon)" class="bookmarks-group-icon" />
205                  <span v-else class="i-lucide:file-text bookmarks-group-icon" />
206                  <span class="bookmarks-group-text">{{ group.card?.title ?? group.path }}</span>
207                </h3>
208                <ul class="bookmarks-list">
209                  <li v-for="bm in group.items" :key="bm.anchor" class="bookmarks-item">
210                    <a class="bookmarks-item-link" :href="bm.path + '#' + bm.anchor" @click="isOpen = false">
211                      <Hash :size="12" :stroke-width="2" class="bookmarks-item-icon" />
212                      {{ bm.title }}
213                    </a>
214                    <button type="button" class="bookmarks-item-remove" :aria-label="`Remove bookmark for ${bm.title}`" @click.stop="remove(bm.anchor, bm.path)">
215                      <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
216                    </button>
217                  </li>
218                </ul>
219              </div>
220
221              <!-- Folder group (e.g. Guides, Glossary) -->
222              <div v-else class="bookmarks-group">
223                <h3 class="bookmarks-group-title">
224                  <span v-if="group.parentCard" :class="cardIconToClass(group.parentCard.icon)" class="bookmarks-group-icon" />
225                  <span v-else class="i-lucide:folder bookmarks-group-icon" />
226                  <span class="bookmarks-group-text">{{ group.section }}</span>
227                </h3>
228                <div v-for="page in group.pages" :key="page.path" class="bookmarks-sub-group">
229                  <h4 class="bookmarks-sub-title">{{ page.card?.title ?? page.path }}</h4>
230                  <ul class="bookmarks-list">
231                    <li v-for="bm in page.items" :key="bm.anchor" class="bookmarks-item">
232                      <a class="bookmarks-item-link" :href="bm.path + '#' + bm.anchor" @click="isOpen = false">
233                        <Hash :size="12" :stroke-width="2" class="bookmarks-item-icon" />
234                        {{ bm.title }}
235                      </a>
236                      <button type="button" class="bookmarks-item-remove" :aria-label="`Remove bookmark for ${bm.title}`" @click.stop="remove(bm.anchor, bm.path)">
237                        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
238                      </button>
239                    </li>
240                  </ul>
241                </div>
242              </div>
243
244            </template>
245          </div>
246        </div>
247        <Transition name="bookmarks-fade">
248          <div v-if="showFade && bookmarks.length > 0" class="bookmarks-fade-overlay" />
249        </Transition>
250      </div>
251    </Transition>
252  </div>
253</template>
254
255<style scoped>
256.bookmarks-wrapper {
257  position: relative;
258  width: 100%;
259  height: 100%;
260  display: flex;
261  align-items: center;
262  justify-content: center;
263}
264
265.bookmarks-btn {
266  display: flex;
267  align-items: center;
268  justify-content: center;
269  width: 100%;
270  height: 100%;
271  color: var(--vp-c-text-1);
272  opacity: 0.55;
273  transition:
274    opacity 0.25s,
275    transform 0.2s cubic-bezier(0.16, 1, 0.3, 1);
276}
277
278.bookmarks-btn:hover { opacity: 1; }
279.bookmarks-btn:active { transform: scale(0.94); }
280
281.bookmarks-panel {
282  position: absolute;
283  top: calc(var(--vp-nav-height) / 2 + 20px);
284  left: var(--bookmarks-panel-left, 50%);
285  z-index: 100;
286  width: 282px;
287  max-width: calc(100vw - 24px);
288  --bm-panel-bg: var(--vp-c-bg-elv);
289  background-color: var(--bm-panel-bg);
290  border: 1px solid var(--vp-c-divider);
291  border-radius: 12px;
292  box-shadow: var(--vp-shadow-3);
293  transition: background-color 0.5s;
294  transform: translateX(var(--bookmarks-panel-shift, -50%));
295  transform-origin: top center;
296  overflow: hidden;
297}
298
299.bookmarks-scroll {
300  height: 400px;
301  overflow-y: auto;
302  overflow-x: hidden;
303  overscroll-behavior: contain;
304  padding: 20px;
305  scrollbar-width: none;
306  -ms-overflow-style: none;
307}
308
309.bookmarks-scroll::-webkit-scrollbar {
310  display: none;
311}
312
313.bookmarks-fade-overlay {
314  position: absolute;
315  bottom: 0;
316  left: 0;
317  right: 0;
318  height: 56px;
319  pointer-events: none;
320  background: linear-gradient(
321    to bottom,
322    transparent,
323    var(--bm-panel-bg)
324  );
325  border-radius: 0 0 12px 12px;
326}
327
328.bookmarks-empty {
329  display: flex;
330  flex-direction: column;
331  align-items: center;
332  justify-content: center;
333  min-height: 360px;
334  gap: 10px;
335  text-align: center;
336  overflow: hidden;
337}
338
339.bookmarks-empty-kaomoji {
340  font-size: 28px;
341  color: var(--vp-c-text-3);
342  line-height: 1;
343  user-select: none;
344}
345
346.bookmarks-empty-hint {
347  font-size: 13px;
348  color: var(--vp-c-text-2);
349  line-height: 1.6;
350  margin: 0;
351  white-space: normal;
352  overflow-wrap: break-word;
353  word-break: break-word;
354}
355
356.bookmarks-empty-hint--mobile {
357  display: none;
358}
359
360.bookmarks-empty-inline-icon {
361  display: inline;
362  vertical-align: middle;
363  position: relative;
364  top: -1px;
365}
366
367.bookmarks-groups {
368  display: flex;
369  flex-direction: column;
370  gap: 8px;
371}
372
373.bookmarks-sub-group {
374  margin-top: 4px;
375}
376
377.bookmarks-sub-title {
378  font-size: 11px;
379  font-weight: 600;
380  letter-spacing: 0;
381  color: var(--vp-c-text-3);
382  margin: 6px 0 2px;
383  padding: 0 6px 4px;
384  user-select: none;
385  border-bottom: 1px solid #525252;
386}
387
388.bookmarks-group-title {
389  display: flex;
390  align-items: center;
391  gap: 6px;
392  font-size: 16px;
393  font-weight: 500;
394  color: var(--vp-c-text-1);
395  margin: 0 0 2px;
396  padding: 2px 0;
397  user-select: none;
398  min-width: 0;
399}
400
401.bookmarks-group-icon {
402  font-size: 16px;
403  color: var(--vp-c-text-1);
404  flex: none;
405}
406
407.bookmarks-group-text {
408  flex: 1;
409  min-width: 0;
410  overflow: hidden;
411  white-space: nowrap;
412  text-overflow: ellipsis;
413}
414
415.bookmarks-list {
416  list-style: none;
417  padding: 0;
418  margin: 0;
419}
420
421.bookmarks-item {
422  display: flex;
423  align-items: center;
424  border-radius: 6px;
425  transition: background-color 0.15s;
426}
427
428.bookmarks-item:hover {
429  background: var(--vp-c-default-soft);
430}
431
432.bookmarks-item-link {
433  display: flex;
434  align-items: center;
435  gap: 5px;
436  flex: 1;
437  padding: 4px 6px;
438  font-size: 13px;
439  color: var(--vp-c-text-2);
440  text-decoration: none;
441  white-space: nowrap;
442  overflow: hidden;
443  text-overflow: ellipsis;
444  transition: color 0.15s;
445  min-width: 0;
446}
447
448.bookmarks-item-link:hover {
449  color: var(--vp-c-brand-1);
450}
451
452.bookmarks-item-icon {
453  flex: none;
454  color: var(--vp-c-text-3);
455}
456
457.bookmarks-item-remove {
458  flex: none;
459  display: flex;
460  align-items: center;
461  justify-content: center;
462  width: 20px;
463  height: 20px;
464  margin-right: 4px;
465  border: none;
466  background: transparent;
467  color: var(--vp-c-text-3);
468  cursor: pointer;
469  transition: color 0.15s;
470}
471
472.bookmarks-item-remove:hover {
473  color: var(--vp-c-text-1);
474}
475
476.bookmarks-panel-enter-active,
477.bookmarks-panel-leave-active {
478  transition: opacity 0.15s, transform 0.15s cubic-bezier(0.16, 1, 0.3, 1);
479}
480
481.bookmarks-panel-enter-from,
482.bookmarks-panel-leave-to {
483  opacity: 0;
484  transform: translateX(var(--bookmarks-panel-shift, -50%)) scale(0.95) translateY(-4px);
485}
486
487.bookmarks-fade-enter-active,
488.bookmarks-fade-leave-active {
489  transition: opacity 0.2s;
490}
491
492.bookmarks-fade-enter-from,
493.bookmarks-fade-leave-to {
494  opacity: 0;
495}
496
497.bookmarks-mobile-header {
498  display: none;
499}
500
501@media (max-width: 1279px) {
502  .bookmarks-empty-hint--desktop {
503    display: none;
504  }
505
506  .bookmarks-empty-hint--mobile {
507    display: block;
508  }
509}
510
511@media (max-width: 767px) {
512  .bookmarks-panel {
513    position: fixed;
514    top: 0;
515    left: 0;
516    right: 0;
517    bottom: 0;
518    width: 100%;
519    max-width: none;
520    height: 100%;
521    border-radius: 0;
522    border: none;
523    z-index: 9999;
524    transform: none;
525    transform-origin: center top;
526    display: flex;
527    flex-direction: column;
528    --bm-panel-bg: var(--vp-c-bg);
529  }
530
531  .bookmarks-scroll {
532    flex: 1;
533    height: auto;
534    min-height: 0;
535    display: flex;
536    flex-direction: column;
537  }
538
539  .bookmarks-empty {
540    flex: 1;
541    min-height: 0;
542  }
543
544  .bookmarks-mobile-header {
545    display: flex;
546    align-items: center;
547    height: 49px;
548    flex-shrink: 0;
549    padding: 6px 8px;
550    border-bottom: 1px solid var(--wk-fs-header-divider);
551  }
552
553  .bookmarks-mobile-title {
554    font-size: 16px;
555    font-weight: 600;
556    color: var(--vp-c-text-1);
557  }
558
559  .bookmarks-mobile-back {
560    display: flex;
561    align-items: center;
562    justify-content: center;
563    padding: 8px;
564    border: none;
565    background: transparent;
566    color: var(--vp-c-text-1);
567    cursor: pointer;
568    transition: color 0.15s;
569  }
570
571  .bookmarks-mobile-back:hover {
572    color: var(--vp-c-brand-1);
573  }
574
575  .bookmarks-panel-enter-from,
576  .bookmarks-panel-leave-to {
577    opacity: 0;
578    transform: translateY(8px);
579  }
580}
581</style>