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