docs/.vitepress/theme/Layout.vue
1201 lines · 35259 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 { AccentColorStorageKey, LowEndDeviceModeStorageKey, TakodachiStorageKey } from './constants'
38import { v2add, v2mag, v2norm, v2smul, v2sub, type Vec2D } from './math'
39
40const route = useRoute()
41const { frontmatter, isDark, 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 })
70}
71
72const nextFrame = () =>
73 new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
74
75const getSearchTerms = (query: string) =>
76 query
77 .toLowerCase()
78 .split(/\s+/)
79 .map((term) => term.trim())
80 .filter(Boolean)
81
82const getTargetByHash = (hash: string) => {
83 const ids = [hash]
84 try {
85 const decoded = decodeURIComponent(hash)
86 if (decoded !== hash) ids.unshift(decoded)
87 } catch {
88 /* keep the raw hash */
89 }
90
91 for (const id of ids) {
92 const target = document.getElementById(id)
93 if (target) return target
94 }
95}
96
97const getScrollTargetForAnchor = (target: HTMLElement) => {
98 if (target.classList.contains('tab-search-heading')) {
99 return target.closest<HTMLElement>('.plugin-tabs') ?? target
100 }
101
102 return target
103}
104
105const TAB_QUERY_PARAM = 'tabs'
106
107const getRequestedTabPath = () => {
108 const value = new URLSearchParams(window.location.search).get(
109 TAB_QUERY_PARAM
110 )
111 return value
112 ?.split(',')
113 .map((tab) => tab.trim())
114 .filter(Boolean) ?? []
115}
116
117const buildUrlWithTabs = (tabs: string[], hash = '') => {
118 const params = new URLSearchParams(window.location.search)
119 params.delete(TAB_QUERY_PARAM)
120
121 const queryParts = [
122 params.toString(),
123 tabs.length
124 ? `${TAB_QUERY_PARAM}=${
125 tabs.map((tab) => encodeURIComponent(tab)).join(',')
126 }`
127 : ''
128 ].filter(Boolean)
129
130 return `${window.location.pathname}${
131 queryParts.length ? `?${queryParts.join('&')}` : ''
132 }${hash ? `#${encodeURIComponent(hash)}` : ''}`
133}
134
135const getSelectedTabAnchor = (tabs: HTMLElement) =>
136 tabs.querySelector<HTMLButtonElement>(
137 '.plugin-tabs--tab[aria-selected="true"][data-tab-anchor]'
138 )?.dataset.tabAnchor
139
140const getPanelForTabButton = (button: HTMLButtonElement) => {
141 const panelId = button.getAttribute('aria-controls')
142 return panelId ? document.getElementById(panelId) : undefined
143}
144
145const getTabPathForGroup = (tabs: HTMLElement) => {
146 const groups: HTMLElement[] = []
147 let currentTabs: HTMLElement | null = tabs
148
149 while (currentTabs) {
150 groups.unshift(currentTabs)
151 const parentPanel = currentTabs.parentElement?.closest<HTMLElement>(
152 '.plugin-tabs--content[data-tab-anchor]'
153 )
154 currentTabs = parentPanel?.closest<HTMLElement>('.plugin-tabs') ?? null
155 }
156
157 return groups
158 .map((group) => getSelectedTabAnchor(group))
159 .filter((tab): tab is string => Boolean(tab))
160}
161
162const updateQueryForSelectedTab = async (tabs: HTMLElement) => {
163 await nextTick()
164 await nextFrame()
165
166 const tabPath = getTabPathForGroup(tabs)
167 if (!tabPath.length) return
168
169 const nextUrl = buildUrlWithTabs(tabPath)
170 const currentUrl =
171 `${window.location.pathname}${window.location.search}${window.location.hash}`
172 if (nextUrl === currentUrl) return
173
174 window.history.pushState(null, '', nextUrl)
175 rewriteAnchorLinks()
176}
177
178const queueTabQueryUpdateForSelection = (target: EventTarget | null) => {
179 if (!(target instanceof HTMLElement)) return
180
181 const button = target.closest<HTMLButtonElement>(
182 '.plugin-tabs--tab[role="tab"]'
183 )
184 const tabs = button?.closest<HTMLElement>('.plugin-tabs')
185 if (tabs) void updateQueryForSelectedTab(tabs)
186}
187
188const TAB_LINK_MARKER = 'tab-'
189
190const rewriteAnchorLinks = () => {
191 const origin = window.location.origin
192 const pathname = window.location.pathname
193
194 document
195 .querySelectorAll<HTMLAnchorElement>('.VPDoc .vp-doc a[href]')
196 .forEach((link) => {
197 // Accept either the original `#…` form or a previously-rewritten absolute URL.
198 const raw = link.getAttribute('href') ?? ''
199 let fragment: string | null = null
200 if (raw.startsWith('#') && raw.length > 1) {
201 fragment = raw.slice(1)
202 } else if (raw.startsWith(origin + pathname + '#')) {
203 fragment = raw.slice((origin + pathname + '#').length)
204 } else if (raw.startsWith(origin + pathname + '?')) {
205 // Already rewritten as a tab link — re-derive the tab name and re-stamp.
206 const qs = raw.slice((origin + pathname + '?').length).split('#')[0]
207 const tabName = new URLSearchParams(qs).get(TAB_QUERY_PARAM)
208 if (tabName) {
209 const href = `${origin}${pathname}?${TAB_QUERY_PARAM}=${
210 encodeURIComponent(tabName)
211 }`
212 if (link.getAttribute('href') !== href) {
213 link.setAttribute('href', href)
214 }
215 }
216 return
217 } else {
218 return
219 }
220
221 const isTabLink = fragment.startsWith(TAB_LINK_MARKER)
222 const name = (isTabLink
223 ? fragment.slice(TAB_LINK_MARKER.length)
224 : fragment).trim()
225 if (!name) return
226
227 // Use absolute URLs so the browser's Copy Link has nothing to merge with
228 // the current ?tabs= query.
229 const href = isTabLink
230 ? `${origin}${pathname}?${TAB_QUERY_PARAM}=${encodeURIComponent(name)}`
231 : `${origin}${pathname}#${name}`
232
233 if (link.getAttribute('href') !== href) link.setAttribute('href', href)
234 })
235}
236
237const selectTabsByPath = async (tabPath: string[]) => {
238 let root: ParentNode = document
239 let selectedTabs: HTMLElement | undefined
240
241 for (const anchor of tabPath) {
242 const button = root.querySelector<HTMLButtonElement>(
243 `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(anchor)}"]`
244 )
245 if (!button) return selectedTabs
246
247 const tabs = button.closest<HTMLElement>('.plugin-tabs')
248 if (!tabs) return selectedTabs
249
250 selectedTabs = tabs
251 if (button.getAttribute('aria-selected') !== 'true') {
252 button.click()
253 await nextTick()
254 await nextFrame()
255 }
256
257 root = getPanelForTabButton(button) ?? tabs
258 }
259
260 return selectedTabs
261}
262
263const selectLegacyTabHash = async (hash: string) => {
264 const button = document.querySelector<HTMLButtonElement>(
265 `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(hash)}"]`
266 )
267 if (!button) return
268
269 if (button.getAttribute('aria-selected') !== 'true') {
270 button.click()
271 await nextTick()
272 await nextFrame()
273 }
274
275 const tabs = button.closest<HTMLElement>('.plugin-tabs')
276 if (tabs) {
277 window.history.replaceState(null, '', buildUrlWithTabs([hash]))
278 }
279 return tabs
280}
281
282const getSelectedTabScrollTarget = (tabs: HTMLElement) => {
283 const selectedTab = tabs.querySelector<HTMLButtonElement>(
284 '.plugin-tabs--tab[aria-selected="true"]'
285 )
286 return selectedTab ? getPanelForTabButton(selectedTab) ?? tabs : tabs
287}
288
289const scrollToElement = (target: HTMLElement, smooth = true) => {
290 requestAnimationFrame(() => {
291 requestAnimationFrame(() => {
292 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
293 const navOffset = navBar ? navBar.offsetHeight : 0
294 window.scrollTo({
295 top: target.getBoundingClientRect().top + window.scrollY - navOffset,
296 behavior: smooth &&
297 !window.matchMedia('(prefers-reduced-motion: reduce)').matches
298 ? 'smooth'
299 : 'auto'
300 })
301 target.setAttribute('tabindex', '-1')
302 target.focus({ preventScroll: true })
303 })
304 })
305}
306
307const openCollapsibles = async (target: HTMLElement) => {
308 const activeTarget = target
309 let scrollTarget = getScrollTargetForAnchor(activeTarget)
310 let el: HTMLElement | null = activeTarget
311
312 while ((el = el.closest('details'))) {
313 el.open = true
314 scrollTarget = el
315 el = el.parentElement
316 }
317
318 const tagName = activeTarget.tagName
319 if (tagName.length === 2 && tagName[0] === 'H') {
320 const level = +tagName[1]
321 if (level >= 1 && level <= 6) {
322 const terms = getSearchTerms(searchQuery)
323 const detailsContainsTerms = (d: HTMLElement) => {
324 if (!terms.length) return false
325 const text = (d.textContent ?? '').toLowerCase()
326 return terms.every((term) => text.includes(term))
327 }
328
329 let sibling = activeTarget.nextElementSibling
330
331 while (sibling) {
332 const siblingTag = sibling.tagName
333 if (
334 siblingTag.length === 2 && siblingTag[0] === 'H' &&
335 +siblingTag[1] <= level
336 ) break
337
338 if (siblingTag === 'DETAILS') {
339 if (detailsContainsTerms(sibling as HTMLElement)) {
340 ;(sibling as HTMLDetailsElement).open = true
341 if (scrollTarget === activeTarget) {
342 scrollTarget = sibling as HTMLElement
343 }
344 }
345 }
346
347 const nested = sibling.getElementsByTagName('details')
348 for (let i = 0, len = nested.length; i < len; i++) {
349 if (detailsContainsTerms(nested[i])) {
350 nested[i].open = true
351 if (scrollTarget === activeTarget) scrollTarget = nested[i]
352 }
353 }
354
355 sibling = sibling.nextElementSibling
356 }
357 }
358 }
359
360 await nextTick()
361 await nextFrame()
362
363 scrollToElement(scrollTarget)
364}
365
366const resetSearchNavigation = () => {
367 searchNavigated = false
368 searchQuery = ''
369}
370
371const tryOpenAnchoredContent = async () => {
372 await nextTick()
373 await nextFrame()
374
375 const requestedTabs = getRequestedTabPath()
376 const selectedTabs = requestedTabs.length
377 ? await selectTabsByPath(requestedTabs)
378 : undefined
379 const hash = window.location.hash.slice(1)
380
381 if (!hash) {
382 resetSearchNavigation()
383 if (selectedTabs) {
384 scrollToElement(getSelectedTabScrollTarget(selectedTabs), false)
385 }
386 return
387 }
388
389 let target = getTargetByHash(hash)
390
391 if (!target && !requestedTabs.length) {
392 const legacyTabs = await selectLegacyTabHash(hash)
393 if (legacyTabs) {
394 resetSearchNavigation()
395 scrollToElement(getSelectedTabScrollTarget(legacyTabs), false)
396 return
397 }
398 }
399
400 if (!target) {
401 if (searchNavigated) resetSearchNavigation()
402 return
403 }
404
405 if (searchNavigated) {
406 await openCollapsibles(target)
407 resetSearchNavigation()
408 return
409 }
410
411 const isTabRelatedTarget = target.classList.contains('tab-search-heading') ||
412 Boolean(target.closest('.plugin-tabs'))
413
414 if (
415 !isTabRelatedTarget &&
416 new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)
417 ) {
418 window.history.replaceState(null, '', buildUrlWithTabs([], hash))
419 scrollToElement(getScrollTargetForAnchor(target), false)
420 return
421 }
422
423 if (
424 !requestedTabs.length && target.classList.contains('tab-search-heading')
425 ) {
426 const tabs = target.closest<HTMLElement>('.plugin-tabs')
427 if (tabs) {
428 window.history.replaceState(
429 null,
430 '',
431 buildUrlWithTabs(getTabPathForGroup(tabs))
432 )
433 }
434 }
435
436 if (
437 selectedTabs ||
438 target.classList.contains('tab-search-heading')
439 ) {
440 scrollToElement(getScrollTargetForAnchor(target), false)
441 }
442}
443
444const rewriteAnchorLinksDeferred = () => nextTick(() => rewriteAnchorLinks())
445
446let outlineFollowObserver: MutationObserver | null = null
447let outlineFollowRaf = 0
448
449const followActiveOutlineLink = () => {
450 cancelAnimationFrame(outlineFollowRaf)
451
452 outlineFollowRaf = requestAnimationFrame(() => {
453 const activeLink = document.querySelector<HTMLElement>(
454 '.VPDocAsideOutline a.outline-link.active'
455 )
456 const scroller = activeLink?.closest<HTMLElement>('.aside-container')
457 if (!activeLink || !scroller) return
458
459 const linkRect = activeLink.getBoundingClientRect()
460 const scrollerRect = scroller.getBoundingClientRect()
461 const margin = 32
462
463 if (linkRect.top < scrollerRect.top + margin) {
464 scroller.scrollTop += linkRect.top - scrollerRect.top - margin
465 } else if (linkRect.bottom > scrollerRect.bottom - margin) {
466 scroller.scrollTop += linkRect.bottom - scrollerRect.bottom + margin
467 }
468 })
469}
470
471const setupOutlineFollow = () => {
472 outlineFollowObserver?.disconnect()
473 outlineFollowObserver = null
474
475 const outline = document.querySelector('.VPDocAsideOutline')
476 if (!outline) return
477
478 outlineFollowObserver = new MutationObserver((mutations) => {
479 if (
480 mutations.some((mutation) =>
481 mutation.type === 'childList' ||
482 (mutation.target instanceof HTMLElement &&
483 mutation.target.matches('a.outline-link'))
484 )
485 ) {
486 followActiveOutlineLink()
487 }
488 })
489
490 outlineFollowObserver.observe(outline, {
491 attributes: true,
492 attributeFilter: ['class'],
493 childList: true,
494 subtree: true
495 })
496 followActiveOutlineLink()
497}
498
499onMounted(tryOpenAnchoredContent)
500onMounted(rewriteAnchorLinksDeferred)
501onMounted(() => nextTick(setupOutlineFollow))
502watch(() => route.data, () => {
503 void tryOpenAnchoredContent()
504 rewriteAnchorLinksDeferred()
505 nextTick(setupOutlineFollow)
506 nextTick(setupManualCopyButtons)
507}, { flush: 'post' })
508watch(() => route.query, () => {
509 void tryOpenAnchoredContent()
510 rewriteAnchorLinksDeferred()
511}, { flush: 'post' })
512watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
513
514function onSidebarEnter() {
515 sidebarRef.value?.focus()
516}
517
518interface BreadcrumbItem {
519 text: string
520 link?: string
521}
522
523const buildBreadcrumbs = (
524 items: Theme.SidebarItem[],
525 currentPath: string
526): BreadcrumbItem[] => {
527 for (const item of items) {
528 // Check if this item matches the current path
529 if (item.link === currentPath) {
530 return [
531 {
532 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
533 link: item.link
534 }
535 ]
536 }
537
538 // Check nested items
539 if (item.items) {
540 const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
541 if (nestedBreadcrumbs.length > 0) {
542 return [
543 {
544 text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
545 link: item.link
546 },
547 ...nestedBreadcrumbs
548 ]
549 }
550 }
551 }
552 return []
553}
554
555const breadcrumbs = computed(() => {
556 const currentPath = route.path
557 // @ts-expect-error
558 return buildBreadcrumbs(sidebar, currentPath)
559})
560
561// Respect user's reduced motion preferences
562const prefs = usePreferredReducedMotion()
563const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
564const reduceBlurEffects = computed(() => lowEndDeviceMode.value === 'on')
565
566watchEffect(() => {
567 if (import.meta.env.SSR) return
568
569 document.documentElement.classList.toggle(
570 'reduce-blur-effects',
571 reduceBlurEffects.value
572 )
573})
574
575type ShadeMap = Record<string, string>
576type PaletteEntry = ShadeMap | { dark: ShadeMap; light: ShadeMap }
577
578const accentPalettes: Record<string, PaletteEntry> = {
579 ayanami: {
580 400: 'oklch(0.722 0.105 247.48)',
581 500: 'oklch(0.626 0.098 247.46)',
582 600: 'oklch(0.523 0.081 246.86)',
583 700: 'oklch(0.43 0.066 246.75)',
584 800: 'oklch(0.335 0.052 246.76)',
585 },
586 asuka: {
587 400: 'oklch(0.740 0.210 32)',
588 500: 'oklch(0.650 0.240 30)',
589 600: 'oklch(0.555 0.238 28)',
590 700: 'oklch(0.455 0.205 26)',
591 800: 'oklch(0.370 0.165 24)',
592 },
593 irys: {
594 400: 'oklch(0.716 0.188 5.18)',
595 500: 'oklch(0.659 0.237 8.99)',
596 600: 'oklch(0.584 0.229 10.32)',
597 700: 'oklch(0.538 0.213 9.67)',
598 800: 'oklch(0.475 0.187 5.94)',
599 },
600 inanis: {
601 400: 'oklch(0.762 0.073 302.02)',
602 500: 'oklch(0.663 0.102 301.22)',
603 600: 'oklch(0.580 0.119 301.34)',
604 700: 'oklch(0.508 0.114 301.00)',
605 800: 'oklch(0.452 0.094 302.20)',
606 },
607 baelz: {
608 400: 'oklch(0.720 0.215 22.00)',
609 500: 'oklch(0.640 0.255 22.00)',
610 600: 'oklch(0.555 0.268 22.00)',
611 700: 'oklch(0.472 0.248 22.00)',
612 800: 'oklch(0.395 0.208 22.00)',
613 },
614 watson: {
615 400: 'oklch(0.800 0.085 75.49)',
616 500: 'oklch(0.710 0.090 72.47)',
617 600: 'oklch(0.594 0.085 69.07)',
618 700: 'oklch(0.496 0.078 72.12)',
619 800: 'oklch(0.391 0.062 68.86)',
620 },
621 suisei: {
622 400: 'oklch(0.827 0.096 224.60)',
623 500: 'oklch(0.740 0.119 230.91)',
624 600: 'oklch(0.645 0.127 236.29)',
625 700: 'oklch(0.548 0.120 241.26)',
626 800: 'oklch(0.451 0.106 244.63)',
627 },
628 miku: {
629 400: 'oklch(0.788 0.133 184.43)',
630 500: 'oklch(0.711 0.123 185.28)',
631 600: 'oklch(0.607 0.104 187.31)',
632 700: 'oklch(0.515 0.086 189.60)',
633 800: 'oklch(0.441 0.071 190.95)',
634 },
635 fubuki: {
636 dark: {
637 400: 'oklch(0.88 0 0)',
638 500: 'oklch(0.78 0 0)',
639 600: 'oklch(0.68 0 0)',
640 700: 'oklch(0.58 0 0)',
641 800: 'oklch(0.48 0 0)',
642 },
643 light: {
644 400: 'oklch(0.52 0 0)',
645 500: 'oklch(0.42 0 0)',
646 600: 'oklch(0.32 0 0)',
647 700: 'oklch(0.22 0 0)',
648 800: 'oklch(0.12 0 0)',
649 },
650 },
651}
652
653const accentColor = useStorage(AccentColorStorageKey, 'ayanami')
654
655watchEffect(() => {
656 if (import.meta.env.SSR) return
657 const palette = accentPalettes[accentColor.value] ?? accentPalettes.ayanami
658 const shades = 'dark' in palette
659 ? (isDark.value ? palette.dark : palette.light)
660 : palette
661 const el = document.documentElement
662 if (isDark.value) {
663 el.style.setProperty('--vp-c-brand-1', shades['400'])
664 el.style.setProperty('--vp-c-brand-2', shades['500'])
665 el.style.setProperty('--vp-c-brand-3', shades['700'])
666 el.style.setProperty('--vp-c-brand-soft', `color-mix(in srgb, ${shades['500']} 20%, transparent)`)
667 el.style.setProperty('--vp-c-sidebar-active', `color-mix(in srgb, ${shades['500']} 15%, transparent)`)
668 } else {
669 el.style.setProperty('--vp-c-brand-1', shades['500'])
670 el.style.setProperty('--vp-c-brand-2', shades['600'])
671 el.style.setProperty('--vp-c-brand-3', shades['800'])
672 el.style.setProperty('--vp-c-brand-soft', `color-mix(in srgb, ${shades['400']} 40%, transparent)`)
673 el.style.setProperty('--vp-c-sidebar-active', `color-mix(in srgb, ${shades['800']} 15%, transparent)`)
674 }
675})
676
677const speed = 2
678const snapThreshold = 5 // px
679
680const takodachiRef = ref<HTMLImageElement | null>(null)
681let mousePos: Vec2D | null = null
682let target: Vec2D | null = null
683let offset: Vec2D = [0, 0]
684
685const position = ref({
686 x: 0,
687 y: 0
688})
689
690const updateMousePos = (e: MouseEvent | TouchEvent) => {
691 if (e instanceof MouseEvent) {
692 mousePos = [e.clientX, e.clientY]
693 } else {
694 mousePos = [e.touches[0].clientX, e.touches[0].clientY]
695 }
696}
697
698const takodachiDisable = ref<(() => void) | null>(null)
699const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
700
701const reloadTakodachi = () => {
702 takodachiDisable.value?.()
703
704 if (prefs.value === 'reduce') return
705 const saved = takodachiToggledOn
706 if (saved.value === false) return
707
708 window.addEventListener('mousemove', updateMousePos)
709 window.addEventListener('touchstart', updateMousePos)
710
711 const chaser = takodachiRef!.value
712 if (chaser) {
713 offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
714 setTimeout(() => {
715 chaser.classList.remove('opacity-0')
716 }, 1000)
717 }
718
719 const intervalId = setInterval(() => {
720 if (!mousePos) return
721
722 const currentPos: Vec2D = [
723 position.value.x + offset[0],
724 position.value.y + offset[1]
725 ]
726
727 target = target ?? currentPos
728
729 const diff = v2sub(mousePos, currentPos)
730
731 target = v2mag(diff) < snapThreshold
732 ? mousePos
733 : v2add(target, v2smul(v2norm(diff), speed))
734
735 const finalVec = v2sub(target, offset)
736
737 position.value = { x: finalVec[0], y: finalVec[1] }
738 }, 10)
739
740 takodachiDisable.value = () => {
741 chaser?.classList.add('opacity-0')
742
743 window.removeEventListener('mousemove', updateMousePos)
744 window.removeEventListener('touchstart', updateMousePos)
745 clearInterval(intervalId)
746
747 takodachiDisable.value = null
748 }
749}
750
751function initTitleOnly() {
752 document.querySelectorAll('.custom-block').forEach(block => {
753 const children = [...block.children]
754 const hasOnlyTitle = children.every(el =>
755 el.classList.contains('custom-block-title')
756 )
757 if (hasOnlyTitle) block.classList.add('title-only')
758 })
759}
760
761function initCopyButtonsInRoot(root: ParentNode) {
762 root.querySelectorAll<HTMLTableElement>('table').forEach(table => {
763 const headers = table.querySelectorAll<HTMLTableCellElement>('thead th')
764 let manualColIndex = -1
765 headers.forEach((th, i) => {
766 if (th.textContent?.trim() === 'Manual') manualColIndex = i
767 })
768 if (manualColIndex === -1) return
769
770 // Track how many more rows each column is occupied by a rowspan from above
771 const colOccupied: number[] = []
772
773 table.querySelectorAll<HTMLTableRowElement>('tbody tr').forEach(row => {
774 const cells = Array.from(row.querySelectorAll('td'))
775 let cellIdx = 0
776 let col = 0
777 let manualCell: HTMLTableCellElement | null = null
778
779 while (col <= manualColIndex) {
780 // Column occupied by a rowspan from a previous row — skip it
781 if ((colOccupied[col] ?? 0) > 0) {
782 colOccupied[col]--
783 col++
784 continue
785 }
786
787 if (cellIdx >= cells.length) break
788 const cell = cells[cellIdx++]
789 const colspan = cell.colSpan || 1
790 const rowspan = cell.rowSpan || 1
791
792 // Register future occupation for rowspan > 1
793 if (rowspan > 1) {
794 for (let c = col; c < col + colspan; c++) {
795 colOccupied[c] = (colOccupied[c] ?? 0) + (rowspan - 1)
796 }
797 }
798
799 if (col <= manualColIndex && col + colspan > manualColIndex) {
800 manualCell = cell
801 }
802
803 col += colspan
804 }
805
806 if (!manualCell || manualCell.querySelector('.manual-copy-btn')) return
807
808 const link = manualCell.querySelector<HTMLAnchorElement>('a[href]')
809 if (!link) return
810 const url = link.getAttribute('href')!
811
812 const btn = document.createElement('button')
813 btn.className = 'manual-copy-btn'
814 btn.title = 'Copy URL'
815 const icon = document.createElement('span')
816 icon.className = 'i-lucide:copy'
817 btn.appendChild(icon)
818
819 btn.addEventListener('click', async (e) => {
820 e.preventDefault()
821 try {
822 await navigator.clipboard.writeText(url)
823 icon.className = 'i-lucide:check'
824 btn.classList.add('copied')
825 setTimeout(() => {
826 icon.className = 'i-lucide:copy'
827 btn.classList.remove('copied')
828 }, 2000)
829 } catch {}
830 })
831
832 manualCell.classList.add('has-manual-copy')
833 manualCell.appendChild(btn)
834 })
835 })
836}
837
838let copyButtonObserver: MutationObserver | null = null
839
840function setupManualCopyButtons() {
841 initCopyButtonsInRoot(document)
842
843 copyButtonObserver?.disconnect()
844 copyButtonObserver = new MutationObserver((mutations) => {
845 for (const mutation of mutations) {
846 for (const node of mutation.addedNodes) {
847 if (!(node instanceof HTMLElement)) continue
848 if (node.classList.contains('plugin-tabs--content')) {
849 initCopyButtonsInRoot(node)
850 } else {
851 node.querySelectorAll<HTMLElement>('.plugin-tabs--content').forEach(
852 panel => initCopyButtonsInRoot(panel)
853 )
854 }
855 }
856 }
857 })
858 copyButtonObserver.observe(document.body, { childList: true, subtree: true })
859}
860
861watch(
862 () => route.path,
863 () => nextTick(() => { initTitleOnly(); setupManualCopyButtons() }),
864 { flush: 'post' }
865)
866
867onMounted(() => {
868 if (import.meta.env.SSR) return
869
870 initTitleOnly()
871 nextTick(setupManualCopyButtons)
872
873 // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
874 const tooltipEl = document.createElement('div')
875 tooltipEl.className = 'icon-tip-popup'
876 document.body.appendChild(tooltipEl)
877
878 const showTooltip = (e: MouseEvent) => {
879 const target = (e.target as HTMLElement).closest('.icon-tip') as
880 | HTMLElement
881 | null
882 if (!target) return
883 const tip = target.dataset.tip
884 if (!tip) return
885
886 tooltipEl.textContent = tip
887 tooltipEl.classList.add('visible')
888
889 const rect = target.getBoundingClientRect()
890 const tipWidth = tooltipEl.offsetWidth
891 const tipHeight = tooltipEl.offsetHeight
892 let left = rect.left + rect.width / 2 - tipWidth / 2
893 left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
894 const top = rect.top - tipHeight - 6
895
896 tooltipEl.style.left = `${left}px`
897 tooltipEl.style.top = `${top}px`
898 }
899
900 const hideTooltip = () => {
901 tooltipEl.classList.remove('visible')
902 }
903
904 document.addEventListener('mouseover', showTooltip)
905 document.addEventListener('mouseout', hideTooltip)
906 document.addEventListener('scroll', hideTooltip, true)
907
908 const onCaptureClick = (e: MouseEvent) => {
909 if (!e.isTrusted) return
910 const link = (e.target as HTMLElement).closest<HTMLAnchorElement>('a[href]')
911 if (!link) return
912 const raw = link.getAttribute('href') ?? ''
913
914 // ── Tab link: #tab-name or already-rewritten /path?tabs=name ──────────
915 const tabFromHash = raw.startsWith('#' + TAB_LINK_MARKER)
916 ? raw.slice(1 + TAB_LINK_MARKER.length)
917 : null
918 let tabFromQuery: string | null = null
919 if (
920 !e.defaultPrevented &&
921 !tabFromHash &&
922 raw.includes(`?${TAB_QUERY_PARAM}=`) &&
923 !raw.includes('#')
924 ) {
925 try {
926 const url = new URL(raw, window.location.href)
927 const samePage = url.origin === window.location.origin &&
928 url.pathname === window.location.pathname
929 tabFromQuery = samePage
930 ? url.searchParams.get(TAB_QUERY_PARAM)
931 : null
932 } catch {
933 tabFromQuery = null
934 }
935 }
936 const tabName = tabFromHash ?? tabFromQuery
937
938 if (tabName) {
939 e.preventDefault()
940 e.stopImmediatePropagation()
941 window.history.pushState(null, '', buildUrlWithTabs([tabName]))
942 rewriteAnchorLinks()
943 void (async () => {
944 const tabs = await selectTabsByPath([tabName])
945 if (tabs) scrollToElement(getSelectedTabScrollTarget(tabs), false)
946 })()
947 return
948 }
949
950 // ── Plain heading link: #name or already-rewritten /path#name ─────────
951 // Only intercept when ?tabs= is present — otherwise let the router handle normally.
952 if (!new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)) {
953 return
954 }
955
956 let hash: string | null = null
957 if (raw.startsWith('#') && raw.length > 1) {
958 hash = raw.slice(1)
959 } else if (raw.startsWith(window.location.pathname + '#')) {
960 hash = raw.slice(window.location.pathname.length + 1)
961 }
962 if (!hash) return
963
964 e.preventDefault()
965 e.stopImmediatePropagation()
966 window.history.pushState(null, '', `${window.location.pathname}#${hash}`)
967 rewriteAnchorLinks()
968 void tryOpenAnchoredContent()
969 }
970
971 document.addEventListener('click', onCaptureClick, { capture: true })
972
973 useEventListener(document, 'click', (e: MouseEvent) => {
974 if (!e.isTrusted) return
975 queueTabQueryUpdateForSelection(e.target)
976 })
977
978 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
979 if (!e.isTrusted || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) {
980 return
981 }
982
983 queueTabQueryUpdateForSelection(e.target)
984 })
985
986 onUnmounted(() => {
987 document.removeEventListener('click', onCaptureClick, { capture: true })
988 document.removeEventListener('mouseover', showTooltip)
989 document.removeEventListener('mouseout', hideTooltip)
990 document.removeEventListener('scroll', hideTooltip, true)
991 tooltipEl.remove()
992 })
993
994 // Arrow key scrolling + Escape close for sidebars and content
995 let activeScrollTarget: HTMLElement | Window = window
996
997 useEventListener(document, 'pointerdown', (e: PointerEvent) => {
998 const el = e.target as HTMLElement
999 if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
1000 activeScrollTarget = sidebarRef.value
1001 } else if (el.closest('.VPSidebar')) {
1002 activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
1003 } else {
1004 activeScrollTarget = window
1005 }
1006 })
1007
1008 const pxPerFrame = 18
1009 let scrollDirection = 0
1010 let scrollRaf = 0
1011
1012 function tickScroll() {
1013 if (!scrollDirection) return
1014 activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
1015 scrollRaf = requestAnimationFrame(tickScroll)
1016 }
1017
1018 function stopScroll() {
1019 scrollDirection = 0
1020 cancelAnimationFrame(scrollRaf)
1021 }
1022
1023 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
1024 if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
1025 return
1026 }
1027
1028 if (e.key === 'Escape') {
1029 if (homeSidebarOpen.value) homeSidebarOpen.value = false
1030 return
1031 }
1032
1033 e.preventDefault()
1034 const dir = e.key === 'ArrowDown' ? 1 : -1
1035 if (scrollDirection === dir) return
1036 scrollDirection = dir
1037 cancelAnimationFrame(scrollRaf)
1038 scrollRaf = requestAnimationFrame(tickScroll)
1039 })
1040
1041 useEventListener(document, 'keyup', (e: KeyboardEvent) => {
1042 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
1043 })
1044
1045 onUnmounted(stopScroll)
1046
1047 // Close home NavScreen on outside click
1048 useEventListener(document, 'click', (e: Event) => {
1049 if (!isHome.value) return
1050 const screen = document.getElementById('VPNavScreen')
1051 if (!screen) return
1052 const hamburger = document.querySelector('.VPNavBarHamburger')
1053 if (
1054 screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
1055 ) return
1056 requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
1057 })
1058
1059 // Storage changed in other documents.
1060 useEventListener(window, 'storage', () => {
1061 reloadTakodachi()
1062 })
1063
1064 // Storage changed in the same document.
1065 useEventListener(window, customStorageEventName, () => {
1066 reloadTakodachi()
1067 })
1068
1069 reloadTakodachi()
1070})
1071
1072onUnmounted(() => {
1073 outlineFollowObserver?.disconnect()
1074 copyButtonObserver?.disconnect()
1075 cancelAnimationFrame(outlineFollowRaf)
1076 takodachiDisable.value && takodachiDisable.value()
1077})
1078</script>
1079
1080<template>
1081 <Layout>
1082 <template #layout-top>
1083 <img
1084 id="takodachi"
1085 ref="takodachiRef"
1086 src="/takodachi.webp"
1087 alt="Takodachi"
1088 class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
1089 :style="{
1090 left: `${position.x}px`,
1091 top: `${position.y}px`
1092 }"
1093 />
1094 <!-- Home sidebar menu -->
1095 <template v-if="isHome">
1096 <Transition name="home-fade">
1097 <div
1098 v-if="homeSidebarOpen"
1099 class="home-sidebar-backdrop"
1100 @click="homeSidebarOpen = false"
1101 />
1102 </Transition>
1103 <Transition name="home-slide" @after-enter="onSidebarEnter">
1104 <aside
1105 v-if="homeSidebarOpen"
1106 ref="sidebarRef"
1107 class="home-sidebar"
1108 tabindex="-1"
1109 @click.stop
1110 >
1111 <div class="home-sidebar-header">
1112 <a href="/" class="home-sidebar-logo">
1113 <img
1114 v-if="logoSrc"
1115 :src="logoSrc"
1116 class="home-sidebar-logo-img"
1117 alt="Logo"
1118 />
1119 <span>{{ theme.siteTitle ?? site.title }}</span>
1120 </a>
1121 </div>
1122 <nav id="VPSidebarNav" class="home-sidebar-nav">
1123 <VPSidebarGroup :items="homeSidebarGroups" />
1124 <SidebarCard />
1125 </nav>
1126 </aside>
1127 </Transition>
1128 </template>
1129 </template>
1130 <template #doc-before>
1131 <!-- Breadcrumb Navigation -->
1132 <nav
1133 v-if="breadcrumbs.length > 0"
1134 class="breadcrumb mb-6 text-sm text-text-2"
1135 aria-label="Breadcrumb"
1136 >
1137 <ol class="flex flex-wrap items-center gap-2">
1138 <li>
1139 <a href="/" class="hover:text-primary transition-colors">
1140 <span class="i-lucide:home"></span>
1141 </a>
1142 </li>
1143 <li
1144 v-for="(crumb, index) in breadcrumbs"
1145 :key="crumb.link || index"
1146 class="flex items-center gap-2"
1147 >
1148 <span
1149 class="i-lucide:chevron-right text-text-3 flex-shrink-0"
1150 ></span>
1151 <span
1152 v-if="index === breadcrumbs.length - 1"
1153 v-html="crumb.text"
1154 class="font-medium text-text-1 break-words"
1155 ></span>
1156 <a
1157 v-else
1158 :href="crumb.link"
1159 v-html="crumb.text"
1160 class="hover:text-primary transition-colors break-words"
1161 ></a>
1162 </li>
1163 </ol>
1164 </nav>
1165 </template>
1166 <template #not-found>
1167 <NotFoundComponent />
1168 </template>
1169 <template #sidebar-nav-after>
1170 <SidebarCard />
1171 </template>
1172 <template #home-hero-info-before>
1173 <AnnouncementPill />
1174 </template>
1175 <template #nav-bar-content-after>
1176 <NolebaseEnhancedReadabilitiesMenu />
1177 </template>
1178 <template #nav-screen-content-before>
1179 <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
1180 <VPSidebarGroup :items="homeSidebarGroups" />
1181 </nav>
1182 </template>
1183 <template #nav-screen-content-after>
1184 <NolebaseEnhancedReadabilitiesScreenMenu />
1185 </template>
1186
1187 <template #nav-bar-title-before>
1188 <span
1189 v-if="isHome"
1190 class="home-menu-btn"
1191 role="button"
1192 tabindex="0"
1193 aria-label="Menu"
1194 @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1195 @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1196 >
1197 <span class="vpi-align-left home-menu-icon" />
1198 </span>
1199 </template>
1200 </Layout>
1201</template>