docs/.vitepress/theme/Layout.vue
613 lines · 17345 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
60let searchQuery = ''
61
62if (!import.meta.env.SSR) {
63 useEventListener(window, 'search-nav', (event) => {
64 searchNavigated = true
65 searchQuery = event instanceof CustomEvent &&
66 typeof event.detail?.query === 'string'
67 ? event.detail.query
68 : ''
69 tryOpenCollapsibles()
70 })
71}
72
73const nextFrame = () =>
74 new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
75
76const getSearchTerms = (query: string) =>
77 query
78 .toLowerCase()
79 .split(/\s+/)
80 .map((term) => term.trim())
81 .filter(Boolean)
82
83const getTabsInSearchScope = (target: HTMLElement) => {
84 const tabs = new Set<HTMLElement>()
85 const closestTabs = target.closest<HTMLElement>('.plugin-tabs')
86 if (closestTabs) tabs.add(closestTabs)
87
88 const tagName = target.tagName
89 if (tagName.length === 2 && tagName[0] === 'H') {
90 const level = +tagName[1]
91 if (level >= 1 && level <= 6) {
92 let sibling = target.nextElementSibling
93
94 while (sibling) {
95 const siblingTag = sibling.tagName
96 if (
97 siblingTag.length === 2 && siblingTag[0] === 'H' &&
98 +siblingTag[1] <= level
99 ) break
100
101 if (sibling.matches('.plugin-tabs')) tabs.add(sibling as HTMLElement)
102 sibling.querySelectorAll<HTMLElement>('.plugin-tabs').forEach((tab) => {
103 tabs.add(tab)
104 })
105
106 sibling = sibling.nextElementSibling
107 }
108 }
109 }
110
111 return [...tabs]
112}
113
114const selectTabContainingQuery = async (target: HTMLElement, query: string) => {
115 const terms = getSearchTerms(query)
116 if (!terms.length) return
117
118 for (const tabs of getTabsInSearchScope(target)) {
119 const selectedTab = tabs.querySelector<HTMLButtonElement>(
120 '.plugin-tabs--tab[aria-selected="true"]'
121 )
122 const buttons = tabs.querySelectorAll<HTMLButtonElement>(
123 '.plugin-tabs--tab[role="tab"]'
124 )
125
126 for (let i = 0, len = buttons.length; i < len; i++) {
127 const button = buttons[i]
128 button.click()
129 await nextTick()
130 await nextFrame()
131
132 const panelId = button.getAttribute('aria-controls')
133 const panel = panelId
134 ? document.getElementById(panelId)
135 : tabs.querySelector<HTMLElement>('.plugin-tabs--content')
136 const text = panel?.textContent?.toLowerCase() ?? ''
137
138 if (terms.every((term) => text.includes(term))) return
139 }
140
141 selectedTab?.click()
142 await nextTick()
143 }
144}
145
146const openCollapsibles = async (target: HTMLElement) => {
147 let scrollTarget = target
148 let el: HTMLElement | null = target
149
150 while ((el = el.closest('details'))) {
151 el.open = true
152 scrollTarget = el
153 el = el.parentElement
154 }
155
156 const tagName = target.tagName
157 if (tagName.length === 2 && tagName[0] === 'H') {
158 const level = +tagName[1]
159 if (level >= 1 && level <= 6) {
160 let sibling = target.nextElementSibling
161
162 while (sibling) {
163 const siblingTag = sibling.tagName
164 if (
165 siblingTag.length === 2 && siblingTag[0] === 'H' &&
166 +siblingTag[1] <= level
167 ) break
168
169 if (siblingTag === 'DETAILS') {
170 ;(sibling as HTMLDetailsElement).open = true
171 if (scrollTarget === target) scrollTarget = sibling as HTMLElement
172 }
173
174 const nested = sibling.getElementsByTagName('details')
175 for (let i = 0, len = nested.length; i < len; i++) {
176 nested[i].open = true
177 if (scrollTarget === target) scrollTarget = nested[i]
178 }
179
180 sibling = sibling.nextElementSibling
181 }
182 }
183 }
184
185 await selectTabContainingQuery(target, searchQuery)
186
187 requestAnimationFrame(() => {
188 requestAnimationFrame(() => {
189 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
190 const navOffset = navBar ? navBar.offsetHeight : 0
191 window.scrollTo({
192 top: scrollTarget.getBoundingClientRect().top + window.scrollY -
193 navOffset,
194 behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches
195 ? 'auto'
196 : 'smooth'
197 })
198 scrollTarget.setAttribute('tabindex', '-1')
199 scrollTarget.focus({ preventScroll: true })
200 })
201 })
202}
203
204const tryOpenCollapsibles = async () => {
205 if (!searchNavigated) return
206 await nextTick()
207
208 requestAnimationFrame(() => {
209 const hash = window.location.hash.slice(1)
210 if (!hash) {
211 searchNavigated = false
212 return
213 }
214
215 const id = decodeURIComponent(hash)
216 const target = document.getElementById(id) || document.getElementById(hash)
217
218 if (target) {
219 openCollapsibles(target)
220 searchNavigated = false
221 searchQuery = ''
222 }
223 })
224}
225
226watch(() => route.data, tryOpenCollapsibles, { flush: 'post' })
227watch(() => route.hash, tryOpenCollapsibles, { flush: 'post' })
228
229function onSidebarEnter() {
230 sidebarRef.value?.focus()
231}
232
233interface BreadcrumbItem {
234 text: string
235 link?: string
236}
237
238const buildBreadcrumbs = (
239 items: Theme.SidebarItem[],
240 currentPath: string
241): BreadcrumbItem[] => {
242 for (const item of items) {
243 // Check if this item matches the current path
244 if (item.link === currentPath) {
245 return [
246 {
247 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
248 link: item.link
249 }
250 ]
251 }
252
253 // Check nested items
254 if (item.items) {
255 const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
256 if (nestedBreadcrumbs.length > 0) {
257 return [
258 {
259 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
260 link: item.link
261 },
262 ...nestedBreadcrumbs
263 ]
264 }
265 }
266 }
267 return []
268}
269
270const breadcrumbs = computed(() => {
271 const currentPath = route.path
272 // @ts-expect-error
273 return buildBreadcrumbs(sidebar, currentPath)
274})
275
276// Respect user's reduced motion preferences
277const prefs = usePreferredReducedMotion()
278const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
279const reduceBlurEffects = computed(() => lowEndDeviceMode.value === 'on')
280
281watchEffect(() => {
282 if (import.meta.env.SSR) return
283
284 document.documentElement.classList.toggle(
285 'reduce-blur-effects',
286 reduceBlurEffects.value
287 )
288})
289
290const speed = 2
291const snapThreshold = 5 // px
292
293const takodachiRef = ref<HTMLImageElement | null>(null)
294let mousePos: Vec2D | null = null
295let target: Vec2D | null = null
296let offset: Vec2D = [0, 0]
297
298const position = ref({
299 x: 0,
300 y: 0
301})
302
303const updateMousePos = (e: MouseEvent | TouchEvent) => {
304 if (e instanceof MouseEvent) {
305 mousePos = [e.clientX, e.clientY]
306 } else {
307 mousePos = [e.touches[0].clientX, e.touches[0].clientY]
308 }
309}
310
311const takodachiDisable = ref<(() => void) | null>(null)
312const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
313
314const reloadTakodachi = () => {
315 takodachiDisable.value?.()
316
317 if (prefs.value === 'reduce') return
318 const saved = takodachiToggledOn
319 if (saved.value === false) return
320
321 window.addEventListener('mousemove', updateMousePos)
322 window.addEventListener('touchstart', updateMousePos)
323
324 const chaser = takodachiRef!.value
325 if (chaser) {
326 offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
327 setTimeout(() => {
328 chaser.classList.remove('opacity-0')
329 }, 1000)
330 }
331
332 const intervalId = setInterval(() => {
333 if (!mousePos) return
334
335 const currentPos: Vec2D = [
336 position.value.x + offset[0],
337 position.value.y + offset[1]
338 ]
339
340 target = target ?? currentPos
341
342 const diff = v2sub(mousePos, currentPos)
343
344 target = v2mag(diff) < snapThreshold
345 ? mousePos
346 : v2add(target, v2smul(v2norm(diff), speed))
347
348 const finalVec = v2sub(target, offset)
349
350 position.value = { x: finalVec[0], y: finalVec[1] }
351 }, 10)
352
353 takodachiDisable.value = () => {
354 chaser?.classList.add('opacity-0')
355
356 window.removeEventListener('mousemove', updateMousePos)
357 window.removeEventListener('touchstart', updateMousePos)
358 clearInterval(intervalId)
359
360 takodachiDisable.value = null
361 }
362}
363
364onMounted(() => {
365 if (import.meta.env.SSR) return
366
367 // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
368 const tooltipEl = document.createElement('div')
369 tooltipEl.className = 'icon-tip-popup'
370 document.body.appendChild(tooltipEl)
371
372 const showTooltip = (e: MouseEvent) => {
373 const target = (e.target as HTMLElement).closest('.icon-tip') as
374 | HTMLElement
375 | null
376 if (!target) return
377 const tip = target.dataset.tip
378 if (!tip) return
379
380 tooltipEl.textContent = tip
381 tooltipEl.classList.add('visible')
382
383 const rect = target.getBoundingClientRect()
384 const tipWidth = tooltipEl.offsetWidth
385 const tipHeight = tooltipEl.offsetHeight
386 let left = rect.left + rect.width / 2 - tipWidth / 2
387 left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
388 const top = rect.top - tipHeight - 6
389
390 tooltipEl.style.left = `${left}px`
391 tooltipEl.style.top = `${top}px`
392 }
393
394 const hideTooltip = () => {
395 tooltipEl.classList.remove('visible')
396 }
397
398 document.addEventListener('mouseover', showTooltip)
399 document.addEventListener('mouseout', hideTooltip)
400 document.addEventListener('scroll', hideTooltip, true)
401
402 onUnmounted(() => {
403 document.removeEventListener('mouseover', showTooltip)
404 document.removeEventListener('mouseout', hideTooltip)
405 document.removeEventListener('scroll', hideTooltip, true)
406 tooltipEl.remove()
407 })
408
409 // Arrow key scrolling + Escape close for sidebars and content
410 let activeScrollTarget: HTMLElement | Window = window
411
412 useEventListener(document, 'pointerdown', (e: PointerEvent) => {
413 const el = e.target as HTMLElement
414 if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
415 activeScrollTarget = sidebarRef.value
416 } else if (el.closest('.VPSidebar')) {
417 activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
418 } else {
419 activeScrollTarget = window
420 }
421 })
422
423 const pxPerFrame = 18
424 let scrollDirection = 0
425 let scrollRaf = 0
426
427 function tickScroll() {
428 if (!scrollDirection) return
429 activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
430 scrollRaf = requestAnimationFrame(tickScroll)
431 }
432
433 function stopScroll() {
434 scrollDirection = 0
435 cancelAnimationFrame(scrollRaf)
436 }
437
438 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
439 if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
440 return
441 }
442
443 if (e.key === 'Escape') {
444 if (homeSidebarOpen.value) homeSidebarOpen.value = false
445 return
446 }
447
448 e.preventDefault()
449 const dir = e.key === 'ArrowDown' ? 1 : -1
450 if (scrollDirection === dir) return
451 scrollDirection = dir
452 cancelAnimationFrame(scrollRaf)
453 scrollRaf = requestAnimationFrame(tickScroll)
454 })
455
456 useEventListener(document, 'keyup', (e: KeyboardEvent) => {
457 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
458 })
459
460 onUnmounted(stopScroll)
461
462 // Close home NavScreen on outside click
463 useEventListener(document, 'click', (e: Event) => {
464 if (!isHome.value) return
465 const screen = document.getElementById('VPNavScreen')
466 if (!screen) return
467 const hamburger = document.querySelector('.VPNavBarHamburger')
468 if (
469 screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
470 ) return
471 requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
472 })
473
474 // Storage changed in other documents.
475 useEventListener(window, 'storage', () => {
476 reloadTakodachi()
477 })
478
479 // Storage changed in the same document.
480 useEventListener(window, customStorageEventName, () => {
481 reloadTakodachi()
482 })
483
484 reloadTakodachi()
485})
486
487onUnmounted(() => {
488 takodachiDisable.value && takodachiDisable.value()
489})
490</script>
491
492<template>
493 <Layout>
494 <template #layout-top>
495 <img
496 id="takodachi"
497 ref="takodachiRef"
498 src="/takodachi.webp"
499 alt="Takodachi"
500 class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
501 :style="{
502 left: `${position.x}px`,
503 top: `${position.y}px`
504 }"
505 />
506 <!-- Home sidebar menu -->
507 <template v-if="isHome">
508 <Transition name="home-fade">
509 <div
510 v-if="homeSidebarOpen"
511 class="home-sidebar-backdrop"
512 @click="homeSidebarOpen = false"
513 />
514 </Transition>
515 <Transition name="home-slide" @after-enter="onSidebarEnter">
516 <aside
517 v-if="homeSidebarOpen"
518 ref="sidebarRef"
519 class="home-sidebar"
520 tabindex="-1"
521 @click.stop
522 >
523 <div class="home-sidebar-header">
524 <a href="/" class="home-sidebar-logo">
525 <img
526 v-if="logoSrc"
527 :src="logoSrc"
528 class="home-sidebar-logo-img"
529 alt="Logo"
530 />
531 <span>{{ theme.siteTitle ?? site.title }}</span>
532 </a>
533 </div>
534 <nav id="VPSidebarNav" class="home-sidebar-nav">
535 <VPSidebarGroup :items="homeSidebarGroups" />
536 <SidebarCard />
537 </nav>
538 </aside>
539 </Transition>
540 </template>
541 </template>
542 <template #doc-before>
543 <!-- Breadcrumb Navigation -->
544 <nav
545 v-if="breadcrumbs.length > 0"
546 class="breadcrumb mb-6 text-sm text-text-2"
547 aria-label="Breadcrumb"
548 >
549 <ol class="flex flex-wrap items-center gap-2">
550 <li>
551 <a href="/" class="hover:text-primary transition-colors">
552 <span class="i-lucide:home"></span>
553 </a>
554 </li>
555 <li
556 v-for="(crumb, index) in breadcrumbs"
557 :key="crumb.link || index"
558 class="flex items-center gap-2"
559 >
560 <span
561 class="i-lucide:chevron-right text-text-3 flex-shrink-0"
562 ></span>
563 <span
564 v-if="index === breadcrumbs.length - 1"
565 v-html="crumb.text"
566 class="font-medium text-text-1 break-words"
567 ></span>
568 <a
569 v-else
570 :href="crumb.link"
571 v-html="crumb.text"
572 class="hover:text-primary transition-colors break-words"
573 ></a>
574 </li>
575 </ol>
576 </nav>
577 </template>
578 <template #not-found>
579 <NotFoundComponent />
580 </template>
581 <template #sidebar-nav-after>
582 <SidebarCard />
583 </template>
584 <template #home-hero-info-before>
585 <AnnouncementPill />
586 </template>
587 <template #nav-bar-content-after>
588 <NolebaseEnhancedReadabilitiesMenu />
589 </template>
590 <template #nav-screen-content-before>
591 <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
592 <VPSidebarGroup :items="homeSidebarGroups" />
593 </nav>
594 </template>
595 <template #nav-screen-content-after>
596 <NolebaseEnhancedReadabilitiesScreenMenu />
597 </template>
598
599 <template #nav-bar-title-before>
600 <span
601 v-if="isHome"
602 class="home-menu-btn"
603 role="button"
604 tabindex="0"
605 aria-label="Menu"
606 @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
607 @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
608 >
609 <span class="vpi-align-left home-menu-icon" />
610 </span>
611 </template>
612 </Layout>
613</template>