docs/.vitepress/theme/Layout.vue
451 lines · 12990 bytes
1<!--
2 All Rights Reserved
3
4 Copyright (c) 2025 taskylizard
5
6 All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7-->
8<script setup lang="ts">
9import {
10 customStorageEventName,
11 useEventListener,
12 useStorage
13} from '@vueuse/core'
14import { usePreferredReducedMotion } from '@vueuse/core'
15import { useData, useRoute } from 'vitepress'
16import type { DefaultTheme as Theme } from 'vitepress'
17import DefaultTheme from 'vitepress/theme'
18import VPSidebarGroup from 'vitepress/dist/client/theme-default/components/VPSidebarGroup.vue'
19import { getSidebarGroups } from 'vitepress/dist/client/theme-default/support/sidebar'
20import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
21import { sidebar } from '../configs/constants'
22import AnnouncementPill from './components/AnnouncementPill.vue'
23import NotFoundComponent from './components/NotFound.vue'
24import {
25 NolebaseEnhancedReadabilitiesMenu
26} from './components/settings'
27import SidebarCard from './components/SidebarCard.vue'
28import { TakodachiStorageKey } from './constants'
29import { v2add, v2mag, v2norm, v2smul, v2sub, type Vec2D } from './math'
30
31const route = useRoute()
32const { frontmatter, site, theme } = useData()
33const { Layout } = DefaultTheme
34
35// Home sidebar menu
36const isHome = computed(() => frontmatter.value.layout === 'home')
37const homeSidebarOpen = ref(false)
38const sidebarRef = ref<HTMLElement | null>(null)
39const homeSidebarGroups = getSidebarGroups(sidebar as any)
40const logoSrc = computed(() =>
41 typeof theme.value.logo === 'string' ? theme.value.logo : theme.value.logo?.src
42)
43
44watch(() => route.path, () => {
45 homeSidebarOpen.value = false
46})
47
48let searchNavigated = false
49
50if (!import.meta.env.SSR) {
51 useEventListener(window, 'search-nav', () => {
52 searchNavigated = true
53 tryOpenCollapsibles()
54 })
55}
56
57const openCollapsibles = (target: HTMLElement) => {
58 let scrollTarget = target
59 let el: HTMLElement | null = target
60
61 while ((el = el.closest('details'))) {
62 el.open = true
63 scrollTarget = el
64 el = el.parentElement
65 }
66
67 const tagName = target.tagName
68 if (tagName.length === 2 && tagName[0] === 'H') {
69 const level = +tagName[1]
70 if (level >= 1 && level <= 6) {
71 let sibling = target.nextElementSibling
72
73 while (sibling) {
74 const siblingTag = sibling.tagName
75 if (siblingTag.length === 2 && siblingTag[0] === 'H' && +siblingTag[1] <= level) break
76
77 if (siblingTag === 'DETAILS') {
78 (sibling as HTMLDetailsElement).open = true
79 if (scrollTarget === target) scrollTarget = sibling as HTMLElement
80 }
81
82 const nested = sibling.getElementsByTagName('details')
83 for (let i = 0, len = nested.length; i < len; i++) {
84 nested[i].open = true
85 if (scrollTarget === target) scrollTarget = nested[i]
86 }
87
88 sibling = sibling.nextElementSibling
89 }
90 }
91 }
92
93 requestAnimationFrame(() => {
94 requestAnimationFrame(() => {
95 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
96 const navOffset = navBar ? navBar.offsetHeight : 0
97 window.scrollTo({
98 top: scrollTarget.getBoundingClientRect().top + window.scrollY - navOffset,
99 behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'
100 })
101 scrollTarget.setAttribute('tabindex', '-1')
102 scrollTarget.focus({ preventScroll: true })
103 })
104 })
105}
106
107const tryOpenCollapsibles = async () => {
108 if (!searchNavigated) return
109 await nextTick()
110
111 requestAnimationFrame(() => {
112 const hash = window.location.hash.slice(1)
113 if (!hash) {
114 searchNavigated = false
115 return
116 }
117
118 const id = decodeURIComponent(hash)
119 const target = document.getElementById(id) || document.getElementById(hash)
120
121 if (target) {
122 openCollapsibles(target)
123 searchNavigated = false
124 }
125 })
126}
127
128watch(() => route.data, tryOpenCollapsibles, { flush: 'post' })
129watch(() => route.hash, tryOpenCollapsibles, { flush: 'post' })
130
131function onSidebarEnter() {
132 sidebarRef.value?.focus()
133}
134
135interface BreadcrumbItem {
136 text: string
137 link?: string
138}
139
140const buildBreadcrumbs = (
141 items: Theme.SidebarItem[],
142 currentPath: string
143): BreadcrumbItem[] => {
144 for (const item of items) {
145 // Check if this item matches the current path
146 if (item.link === currentPath) {
147 return [
148 {
149 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
150 link: item.link
151 }
152 ]
153 }
154
155 // Check nested items
156 if (item.items) {
157 const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
158 if (nestedBreadcrumbs.length > 0) {
159 return [
160 {
161 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
162 link: item.link
163 },
164 ...nestedBreadcrumbs
165 ]
166 }
167 }
168 }
169 return []
170}
171
172const breadcrumbs = computed(() => {
173 const currentPath = route.path
174 // @ts-expect-error
175 return buildBreadcrumbs(sidebar, currentPath)
176})
177
178// Respect user's reduced motion preferences
179const prefs = usePreferredReducedMotion()
180
181const speed = 2
182const snapThreshold = 5 // px
183
184const takodachiRef = ref<HTMLImageElement | null>(null)
185let mousePos: Vec2D | null = null
186let target: Vec2D | null = null
187let offset: Vec2D = [0, 0]
188
189const position = ref({
190 x: 0,
191 y: 0
192})
193
194const updateMousePos = (e: MouseEvent | TouchEvent) => {
195 if (e instanceof MouseEvent) {
196 mousePos = [e.clientX, e.clientY]
197 } else {
198 mousePos = [e.touches[0].clientX, e.touches[0].clientY]
199 }
200}
201
202const takodachiDisable = ref<(() => void) | null>(null)
203const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
204
205const reloadTakodachi = () => {
206 takodachiDisable.value?.()
207
208 if (prefs.value === 'reduce') return
209 const saved = takodachiToggledOn
210 if (saved.value === false) return
211
212 window.addEventListener('mousemove', updateMousePos)
213 window.addEventListener('touchstart', updateMousePos)
214
215 const chaser = takodachiRef!.value
216 if (chaser) {
217 offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
218 setTimeout(() => {
219 chaser.classList.remove('opacity-0')
220 }, 1000)
221 }
222
223 const intervalId = setInterval(() => {
224 if (!mousePos) return
225
226 const currentPos: Vec2D = [
227 position.value.x + offset[0],
228 position.value.y + offset[1]
229 ]
230
231 target = target ?? currentPos
232
233 const diff = v2sub(mousePos, currentPos)
234
235 target = v2mag(diff) < snapThreshold
236 ? mousePos
237 : v2add(target, v2smul(v2norm(diff), speed))
238
239 const finalVec = v2sub(target, offset)
240
241 position.value = { x: finalVec[0], y: finalVec[1] }
242 }, 10)
243
244 takodachiDisable.value = () => {
245 chaser?.classList.add('opacity-0')
246
247 window.removeEventListener('mousemove', updateMousePos)
248 window.removeEventListener('touchstart', updateMousePos)
249 clearInterval(intervalId)
250
251 takodachiDisable.value = null
252 }
253}
254
255onMounted(() => {
256 if (import.meta.env.SSR) return
257
258 // Arrow key scrolling + Escape close for sidebars and content
259 let activeScrollTarget: HTMLElement | Window = window
260
261 useEventListener(document, 'pointerdown', (e: PointerEvent) => {
262 const el = e.target as HTMLElement
263 if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
264 activeScrollTarget = sidebarRef.value
265 } else if (el.closest('.VPSidebar')) {
266 activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
267 } else {
268 activeScrollTarget = window
269 }
270 })
271
272 const pxPerFrame = 18
273 let scrollDirection = 0
274 let scrollRaf = 0
275
276 function tickScroll() {
277 if (!scrollDirection) return
278 activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
279 scrollRaf = requestAnimationFrame(tickScroll)
280 }
281
282 function stopScroll() {
283 scrollDirection = 0
284 cancelAnimationFrame(scrollRaf)
285 }
286
287 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
288 if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') return
289
290 if (e.key === 'Escape') {
291 if (homeSidebarOpen.value) homeSidebarOpen.value = false
292 return
293 }
294
295 e.preventDefault()
296 const dir = e.key === 'ArrowDown' ? 1 : -1
297 if (scrollDirection === dir) return
298 scrollDirection = dir
299 cancelAnimationFrame(scrollRaf)
300 scrollRaf = requestAnimationFrame(tickScroll)
301 })
302
303 useEventListener(document, 'keyup', (e: KeyboardEvent) => {
304 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
305 })
306
307 onUnmounted(stopScroll)
308
309 // Close home NavScreen on outside click
310 useEventListener(document, 'click', (e: Event) => {
311 if (!isHome.value) return
312 const screen = document.getElementById('VPNavScreen')
313 if (!screen) return
314 const hamburger = document.querySelector('.VPNavBarHamburger')
315 if (screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)) return
316 requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
317 })
318
319 // Storage changed in other documents.
320 useEventListener(window, 'storage', () => {
321 reloadTakodachi()
322 })
323
324 // Storage changed in the same document.
325 useEventListener(window, customStorageEventName, () => {
326 reloadTakodachi()
327 })
328
329 reloadTakodachi()
330})
331
332onUnmounted(() => {
333 takodachiDisable.value && takodachiDisable.value()
334})
335</script>
336
337<template>
338 <Layout>
339 <template #layout-top>
340 <img
341 id="takodachi"
342 ref="takodachiRef"
343 src="/takodachi.webp"
344 alt="Takodachi"
345 class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
346 :style="{
347 left: `${position.x}px`,
348 top: `${position.y}px`
349 }"
350 />
351 <!-- Home sidebar menu -->
352 <template v-if="isHome">
353 <Transition name="home-fade">
354 <div
355 v-if="homeSidebarOpen"
356 class="home-sidebar-backdrop"
357 @click="homeSidebarOpen = false"
358 />
359 </Transition>
360 <Transition name="home-slide" @after-enter="onSidebarEnter">
361 <aside
362 v-if="homeSidebarOpen"
363 ref="sidebarRef"
364 class="home-sidebar"
365 tabindex="-1"
366 @click.stop
367 >
368 <div class="home-sidebar-header">
369 <a href="/" class="home-sidebar-logo">
370 <img v-if="logoSrc" :src="logoSrc" class="home-sidebar-logo-img" alt="Logo" />
371 <span>{{ theme.siteTitle ?? site.title }}</span>
372 </a>
373 </div>
374 <nav id="VPSidebarNav" class="home-sidebar-nav">
375 <VPSidebarGroup :items="homeSidebarGroups" />
376 <SidebarCard />
377 </nav>
378 </aside>
379 </Transition>
380 </template>
381 </template>
382 <template #doc-before>
383 <!-- Breadcrumb Navigation -->
384 <nav
385 v-if="breadcrumbs.length > 0"
386 class="breadcrumb mb-6 text-sm text-text-2"
387 aria-label="Breadcrumb"
388 >
389 <ol class="flex flex-wrap items-center gap-2">
390 <li>
391 <a href="/" class="hover:text-primary transition-colors">
392 <span class="i-lucide:home"></span>
393 </a>
394 </li>
395 <li
396 v-for="(crumb, index) in breadcrumbs"
397 :key="crumb.link || index"
398 class="flex items-center gap-2"
399 >
400 <span
401 class="i-lucide:chevron-right text-text-3 flex-shrink-0"
402 ></span>
403 <span
404 v-if="index === breadcrumbs.length - 1"
405 v-html="crumb.text"
406 class="font-medium text-text-1 break-words"
407 ></span>
408 <a
409 v-else
410 :href="crumb.link"
411 v-html="crumb.text"
412 class="hover:text-primary transition-colors break-words"
413 ></a>
414 </li>
415 </ol>
416 </nav>
417 </template>
418 <template #not-found>
419 <NotFoundComponent />
420 </template>
421 <template #sidebar-nav-after>
422 <SidebarCard />
423 </template>
424 <template #home-hero-info-before>
425 <AnnouncementPill />
426 </template>
427 <template #nav-bar-content-after>
428 <NolebaseEnhancedReadabilitiesMenu />
429 </template>
430 <template #nav-screen-content-before>
431 <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
432 <VPSidebarGroup :items="homeSidebarGroups" />
433 </nav>
434 </template>
435 <template #nav-screen-content-after />
436
437 <template #nav-bar-title-before>
438 <span
439 v-if="isHome"
440 class="home-menu-btn"
441 role="button"
442 tabindex="0"
443 aria-label="Menu"
444 @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
445 @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
446 >
447 <span class="vpi-align-left home-menu-icon" />
448 </span>
449 </template>
450 </Layout>
451</template>