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