docs/.vitepress/theme/Layout.vue
1099 lines · 31950 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 })
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
575const speed = 2
576const snapThreshold = 5 // px
577
578const takodachiRef = ref<HTMLImageElement | null>(null)
579let mousePos: Vec2D | null = null
580let target: Vec2D | null = null
581let offset: Vec2D = [0, 0]
582
583const position = ref({
584 x: 0,
585 y: 0
586})
587
588const updateMousePos = (e: MouseEvent | TouchEvent) => {
589 if (e instanceof MouseEvent) {
590 mousePos = [e.clientX, e.clientY]
591 } else {
592 mousePos = [e.touches[0].clientX, e.touches[0].clientY]
593 }
594}
595
596const takodachiDisable = ref<(() => void) | null>(null)
597const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
598
599const reloadTakodachi = () => {
600 takodachiDisable.value?.()
601
602 if (prefs.value === 'reduce') return
603 const saved = takodachiToggledOn
604 if (saved.value === false) return
605
606 window.addEventListener('mousemove', updateMousePos)
607 window.addEventListener('touchstart', updateMousePos)
608
609 const chaser = takodachiRef!.value
610 if (chaser) {
611 offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
612 setTimeout(() => {
613 chaser.classList.remove('opacity-0')
614 }, 1000)
615 }
616
617 const intervalId = setInterval(() => {
618 if (!mousePos) return
619
620 const currentPos: Vec2D = [
621 position.value.x + offset[0],
622 position.value.y + offset[1]
623 ]
624
625 target = target ?? currentPos
626
627 const diff = v2sub(mousePos, currentPos)
628
629 target = v2mag(diff) < snapThreshold
630 ? mousePos
631 : v2add(target, v2smul(v2norm(diff), speed))
632
633 const finalVec = v2sub(target, offset)
634
635 position.value = { x: finalVec[0], y: finalVec[1] }
636 }, 10)
637
638 takodachiDisable.value = () => {
639 chaser?.classList.add('opacity-0')
640
641 window.removeEventListener('mousemove', updateMousePos)
642 window.removeEventListener('touchstart', updateMousePos)
643 clearInterval(intervalId)
644
645 takodachiDisable.value = null
646 }
647}
648
649function initTitleOnly() {
650 document.querySelectorAll('.custom-block').forEach(block => {
651 const children = [...block.children]
652 const hasOnlyTitle = children.every(el =>
653 el.classList.contains('custom-block-title')
654 )
655 if (hasOnlyTitle) block.classList.add('title-only')
656 })
657}
658
659function initCopyButtonsInRoot(root: ParentNode) {
660 root.querySelectorAll<HTMLTableElement>('table').forEach(table => {
661 const headers = table.querySelectorAll<HTMLTableCellElement>('thead th')
662 let manualColIndex = -1
663 headers.forEach((th, i) => {
664 if (th.textContent?.trim() === 'Manual') manualColIndex = i
665 })
666 if (manualColIndex === -1) return
667
668 // Track how many more rows each column is occupied by a rowspan from above
669 const colOccupied: number[] = []
670
671 table.querySelectorAll<HTMLTableRowElement>('tbody tr').forEach(row => {
672 const cells = Array.from(row.querySelectorAll('td'))
673 let cellIdx = 0
674 let col = 0
675 let manualCell: HTMLTableCellElement | null = null
676
677 while (col <= manualColIndex) {
678 // Column occupied by a rowspan from a previous row — skip it
679 if ((colOccupied[col] ?? 0) > 0) {
680 colOccupied[col]--
681 col++
682 continue
683 }
684
685 if (cellIdx >= cells.length) break
686 const cell = cells[cellIdx++]
687 const colspan = cell.colSpan || 1
688 const rowspan = cell.rowSpan || 1
689
690 // Register future occupation for rowspan > 1
691 if (rowspan > 1) {
692 for (let c = col; c < col + colspan; c++) {
693 colOccupied[c] = (colOccupied[c] ?? 0) + (rowspan - 1)
694 }
695 }
696
697 if (col <= manualColIndex && col + colspan > manualColIndex) {
698 manualCell = cell
699 }
700
701 col += colspan
702 }
703
704 if (!manualCell || manualCell.querySelector('.manual-copy-btn')) return
705
706 const link = manualCell.querySelector<HTMLAnchorElement>('a[href]')
707 if (!link) return
708 const url = link.getAttribute('href')!
709
710 const btn = document.createElement('button')
711 btn.className = 'manual-copy-btn'
712 btn.title = 'Copy URL'
713 const icon = document.createElement('span')
714 icon.className = 'i-lucide:copy'
715 btn.appendChild(icon)
716
717 btn.addEventListener('click', async (e) => {
718 e.preventDefault()
719 try {
720 await navigator.clipboard.writeText(url)
721 icon.className = 'i-lucide:check'
722 btn.classList.add('copied')
723 setTimeout(() => {
724 icon.className = 'i-lucide:copy'
725 btn.classList.remove('copied')
726 }, 2000)
727 } catch {}
728 })
729
730 manualCell.classList.add('has-manual-copy')
731 manualCell.appendChild(btn)
732 })
733 })
734}
735
736let copyButtonObserver: MutationObserver | null = null
737
738function setupManualCopyButtons() {
739 initCopyButtonsInRoot(document)
740
741 copyButtonObserver?.disconnect()
742 copyButtonObserver = new MutationObserver((mutations) => {
743 for (const mutation of mutations) {
744 for (const node of mutation.addedNodes) {
745 if (!(node instanceof HTMLElement)) continue
746 if (node.classList.contains('plugin-tabs--content')) {
747 initCopyButtonsInRoot(node)
748 } else {
749 node.querySelectorAll<HTMLElement>('.plugin-tabs--content').forEach(
750 panel => initCopyButtonsInRoot(panel)
751 )
752 }
753 }
754 }
755 })
756 copyButtonObserver.observe(document.body, { childList: true, subtree: true })
757}
758
759watch(
760 () => route.path,
761 () => nextTick(() => { initTitleOnly(); setupManualCopyButtons() }),
762 { flush: 'post' }
763)
764
765onMounted(() => {
766 if (import.meta.env.SSR) return
767
768 initTitleOnly()
769 nextTick(setupManualCopyButtons)
770
771 // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
772 const tooltipEl = document.createElement('div')
773 tooltipEl.className = 'icon-tip-popup'
774 document.body.appendChild(tooltipEl)
775
776 const showTooltip = (e: MouseEvent) => {
777 const target = (e.target as HTMLElement).closest('.icon-tip') as
778 | HTMLElement
779 | null
780 if (!target) return
781 const tip = target.dataset.tip
782 if (!tip) return
783
784 tooltipEl.textContent = tip
785 tooltipEl.classList.add('visible')
786
787 const rect = target.getBoundingClientRect()
788 const tipWidth = tooltipEl.offsetWidth
789 const tipHeight = tooltipEl.offsetHeight
790 let left = rect.left + rect.width / 2 - tipWidth / 2
791 left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
792 const top = rect.top - tipHeight - 6
793
794 tooltipEl.style.left = `${left}px`
795 tooltipEl.style.top = `${top}px`
796 }
797
798 const hideTooltip = () => {
799 tooltipEl.classList.remove('visible')
800 }
801
802 document.addEventListener('mouseover', showTooltip)
803 document.addEventListener('mouseout', hideTooltip)
804 document.addEventListener('scroll', hideTooltip, true)
805
806 const onCaptureClick = (e: MouseEvent) => {
807 if (!e.isTrusted) return
808 const link = (e.target as HTMLElement).closest<HTMLAnchorElement>('a[href]')
809 if (!link) return
810 const raw = link.getAttribute('href') ?? ''
811
812 // ── Tab link: #tab-name or already-rewritten /path?tabs=name ──────────
813 const tabFromHash = raw.startsWith('#' + TAB_LINK_MARKER)
814 ? raw.slice(1 + TAB_LINK_MARKER.length)
815 : null
816 let tabFromQuery: string | null = null
817 if (
818 !e.defaultPrevented &&
819 !tabFromHash &&
820 raw.includes(`?${TAB_QUERY_PARAM}=`) &&
821 !raw.includes('#')
822 ) {
823 try {
824 const url = new URL(raw, window.location.href)
825 const samePage = url.origin === window.location.origin &&
826 url.pathname === window.location.pathname
827 tabFromQuery = samePage
828 ? url.searchParams.get(TAB_QUERY_PARAM)
829 : null
830 } catch {
831 tabFromQuery = null
832 }
833 }
834 const tabName = tabFromHash ?? tabFromQuery
835
836 if (tabName) {
837 e.preventDefault()
838 e.stopImmediatePropagation()
839 window.history.pushState(null, '', buildUrlWithTabs([tabName]))
840 rewriteAnchorLinks()
841 void (async () => {
842 const tabs = await selectTabsByPath([tabName])
843 if (tabs) scrollToElement(getSelectedTabScrollTarget(tabs), false)
844 })()
845 return
846 }
847
848 // ── Plain heading link: #name or already-rewritten /path#name ─────────
849 // Only intercept when ?tabs= is present — otherwise let the router handle normally.
850 if (!new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)) {
851 return
852 }
853
854 let hash: string | null = null
855 if (raw.startsWith('#') && raw.length > 1) {
856 hash = raw.slice(1)
857 } else if (raw.startsWith(window.location.pathname + '#')) {
858 hash = raw.slice(window.location.pathname.length + 1)
859 }
860 if (!hash) return
861
862 e.preventDefault()
863 e.stopImmediatePropagation()
864 window.history.pushState(null, '', `${window.location.pathname}#${hash}`)
865 rewriteAnchorLinks()
866 void tryOpenAnchoredContent()
867 }
868
869 document.addEventListener('click', onCaptureClick, { capture: true })
870
871 useEventListener(document, 'click', (e: MouseEvent) => {
872 if (!e.isTrusted) return
873 queueTabQueryUpdateForSelection(e.target)
874 })
875
876 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
877 if (!e.isTrusted || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) {
878 return
879 }
880
881 queueTabQueryUpdateForSelection(e.target)
882 })
883
884 onUnmounted(() => {
885 document.removeEventListener('click', onCaptureClick, { capture: true })
886 document.removeEventListener('mouseover', showTooltip)
887 document.removeEventListener('mouseout', hideTooltip)
888 document.removeEventListener('scroll', hideTooltip, true)
889 tooltipEl.remove()
890 })
891
892 // Arrow key scrolling + Escape close for sidebars and content
893 let activeScrollTarget: HTMLElement | Window = window
894
895 useEventListener(document, 'pointerdown', (e: PointerEvent) => {
896 const el = e.target as HTMLElement
897 if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
898 activeScrollTarget = sidebarRef.value
899 } else if (el.closest('.VPSidebar')) {
900 activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
901 } else {
902 activeScrollTarget = window
903 }
904 })
905
906 const pxPerFrame = 18
907 let scrollDirection = 0
908 let scrollRaf = 0
909
910 function tickScroll() {
911 if (!scrollDirection) return
912 activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
913 scrollRaf = requestAnimationFrame(tickScroll)
914 }
915
916 function stopScroll() {
917 scrollDirection = 0
918 cancelAnimationFrame(scrollRaf)
919 }
920
921 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
922 if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
923 return
924 }
925
926 if (e.key === 'Escape') {
927 if (homeSidebarOpen.value) homeSidebarOpen.value = false
928 return
929 }
930
931 e.preventDefault()
932 const dir = e.key === 'ArrowDown' ? 1 : -1
933 if (scrollDirection === dir) return
934 scrollDirection = dir
935 cancelAnimationFrame(scrollRaf)
936 scrollRaf = requestAnimationFrame(tickScroll)
937 })
938
939 useEventListener(document, 'keyup', (e: KeyboardEvent) => {
940 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
941 })
942
943 onUnmounted(stopScroll)
944
945 // Close home NavScreen on outside click
946 useEventListener(document, 'click', (e: Event) => {
947 if (!isHome.value) return
948 const screen = document.getElementById('VPNavScreen')
949 if (!screen) return
950 const hamburger = document.querySelector('.VPNavBarHamburger')
951 if (
952 screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
953 ) return
954 requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
955 })
956
957 // Storage changed in other documents.
958 useEventListener(window, 'storage', () => {
959 reloadTakodachi()
960 })
961
962 // Storage changed in the same document.
963 useEventListener(window, customStorageEventName, () => {
964 reloadTakodachi()
965 })
966
967 reloadTakodachi()
968})
969
970onUnmounted(() => {
971 outlineFollowObserver?.disconnect()
972 copyButtonObserver?.disconnect()
973 cancelAnimationFrame(outlineFollowRaf)
974 takodachiDisable.value && takodachiDisable.value()
975})
976</script>
977
978<template>
979 <Layout>
980 <template #layout-top>
981 <img
982 id="takodachi"
983 ref="takodachiRef"
984 src="/takodachi.webp"
985 alt="Takodachi"
986 class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
987 :style="{
988 left: `${position.x}px`,
989 top: `${position.y}px`
990 }"
991 />
992 <!-- Home sidebar menu -->
993 <template v-if="isHome">
994 <Transition name="home-fade">
995 <div
996 v-if="homeSidebarOpen"
997 class="home-sidebar-backdrop"
998 @click="homeSidebarOpen = false"
999 />
1000 </Transition>
1001 <Transition name="home-slide" @after-enter="onSidebarEnter">
1002 <aside
1003 v-if="homeSidebarOpen"
1004 ref="sidebarRef"
1005 class="home-sidebar"
1006 tabindex="-1"
1007 @click.stop
1008 >
1009 <div class="home-sidebar-header">
1010 <a href="/" class="home-sidebar-logo">
1011 <img
1012 v-if="logoSrc"
1013 :src="logoSrc"
1014 class="home-sidebar-logo-img"
1015 alt="Logo"
1016 />
1017 <span>{{ theme.siteTitle ?? site.title }}</span>
1018 </a>
1019 </div>
1020 <nav id="VPSidebarNav" class="home-sidebar-nav">
1021 <VPSidebarGroup :items="homeSidebarGroups" />
1022 <SidebarCard />
1023 </nav>
1024 </aside>
1025 </Transition>
1026 </template>
1027 </template>
1028 <template #doc-before>
1029 <!-- Breadcrumb Navigation -->
1030 <nav
1031 v-if="breadcrumbs.length > 0"
1032 class="breadcrumb mb-6 text-sm text-text-2"
1033 aria-label="Breadcrumb"
1034 >
1035 <ol class="flex flex-wrap items-center gap-2">
1036 <li>
1037 <a href="/" class="hover:text-primary transition-colors">
1038 <span class="i-lucide:home"></span>
1039 </a>
1040 </li>
1041 <li
1042 v-for="(crumb, index) in breadcrumbs"
1043 :key="crumb.link || index"
1044 class="flex items-center gap-2"
1045 >
1046 <span
1047 class="i-lucide:chevron-right text-text-3 flex-shrink-0"
1048 ></span>
1049 <span
1050 v-if="index === breadcrumbs.length - 1"
1051 v-html="crumb.text"
1052 class="font-medium text-text-1 break-words"
1053 ></span>
1054 <a
1055 v-else
1056 :href="crumb.link"
1057 v-html="crumb.text"
1058 class="hover:text-primary transition-colors break-words"
1059 ></a>
1060 </li>
1061 </ol>
1062 </nav>
1063 </template>
1064 <template #not-found>
1065 <NotFoundComponent />
1066 </template>
1067 <template #sidebar-nav-after>
1068 <SidebarCard />
1069 </template>
1070 <template #home-hero-info-before>
1071 <AnnouncementPill />
1072 </template>
1073 <template #nav-bar-content-after>
1074 <NolebaseEnhancedReadabilitiesMenu />
1075 </template>
1076 <template #nav-screen-content-before>
1077 <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
1078 <VPSidebarGroup :items="homeSidebarGroups" />
1079 </nav>
1080 </template>
1081 <template #nav-screen-content-after>
1082 <NolebaseEnhancedReadabilitiesScreenMenu />
1083 </template>
1084
1085 <template #nav-bar-title-before>
1086 <span
1087 v-if="isHome"
1088 class="home-menu-btn"
1089 role="button"
1090 tabindex="0"
1091 aria-label="Menu"
1092 @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1093 @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1094 >
1095 <span class="vpi-align-left home-menu-icon" />
1096 </span>
1097 </template>
1098 </Layout>
1099</template>