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