docs/.vitepress/theme/Layout.vue

e98c43fa5e016871d24182bcea0c93dcb208cec8
wotaku/docs/.vitepress/theme/Layout.vue history · blame · raw

996 lines · 28646 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}, { flush: 'post' })
507watch(() => route.query, () => {
508  void tryOpenAnchoredContent()
509  rewriteAnchorLinksDeferred()
510}, { flush: 'post' })
511watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
512
513function onSidebarEnter() {
514  sidebarRef.value?.focus()
515}
516
517interface BreadcrumbItem {
518  text: string
519  link?: string
520}
521
522const buildBreadcrumbs = (
523  items: Theme.SidebarItem[],
524  currentPath: string
525): BreadcrumbItem[] => {
526  for (const item of items) {
527    // Check if this item matches the current path
528    if (item.link === currentPath) {
529      return [
530        {
531          text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
532          link: item.link
533        }
534      ]
535    }
536
537    // Check nested items
538    if (item.items) {
539      const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
540      if (nestedBreadcrumbs.length > 0) {
541        return [
542          {
543            text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
544            link: item.link
545          },
546          ...nestedBreadcrumbs
547        ]
548      }
549    }
550  }
551  return []
552}
553
554const breadcrumbs = computed(() => {
555  const currentPath = route.path
556  // @ts-expect-error
557  return buildBreadcrumbs(sidebar, currentPath)
558})
559
560// Respect user's reduced motion preferences
561const prefs = usePreferredReducedMotion()
562const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
563const reduceBlurEffects = computed(() => lowEndDeviceMode.value === 'on')
564
565watchEffect(() => {
566  if (import.meta.env.SSR) return
567
568  document.documentElement.classList.toggle(
569    'reduce-blur-effects',
570    reduceBlurEffects.value
571  )
572})
573
574const speed = 2
575const snapThreshold = 5 // px
576
577const takodachiRef = ref<HTMLImageElement | null>(null)
578let mousePos: Vec2D | null = null
579let target: Vec2D | null = null
580let offset: Vec2D = [0, 0]
581
582const position = ref({
583  x: 0,
584  y: 0
585})
586
587const updateMousePos = (e: MouseEvent | TouchEvent) => {
588  if (e instanceof MouseEvent) {
589    mousePos = [e.clientX, e.clientY]
590  } else {
591    mousePos = [e.touches[0].clientX, e.touches[0].clientY]
592  }
593}
594
595const takodachiDisable = ref<(() => void) | null>(null)
596const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
597
598const reloadTakodachi = () => {
599  takodachiDisable.value?.()
600
601  if (prefs.value === 'reduce') return
602  const saved = takodachiToggledOn
603  if (saved.value === false) return
604
605  window.addEventListener('mousemove', updateMousePos)
606  window.addEventListener('touchstart', updateMousePos)
607
608  const chaser = takodachiRef!.value
609  if (chaser) {
610    offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
611    setTimeout(() => {
612      chaser.classList.remove('opacity-0')
613    }, 1000)
614  }
615
616  const intervalId = setInterval(() => {
617    if (!mousePos) return
618
619    const currentPos: Vec2D = [
620      position.value.x + offset[0],
621      position.value.y + offset[1]
622    ]
623
624    target = target ?? currentPos
625
626    const diff = v2sub(mousePos, currentPos)
627
628    target = v2mag(diff) < snapThreshold
629      ? mousePos
630      : v2add(target, v2smul(v2norm(diff), speed))
631
632    const finalVec = v2sub(target, offset)
633
634    position.value = { x: finalVec[0], y: finalVec[1] }
635  }, 10)
636
637  takodachiDisable.value = () => {
638    chaser?.classList.add('opacity-0')
639
640    window.removeEventListener('mousemove', updateMousePos)
641    window.removeEventListener('touchstart', updateMousePos)
642    clearInterval(intervalId)
643
644    takodachiDisable.value = null
645  }
646}
647
648function initTitleOnly() {
649  document.querySelectorAll('.custom-block').forEach(block => {
650    const children = [...block.children]
651    const hasOnlyTitle = children.every(el =>
652      el.classList.contains('custom-block-title')
653    )
654    if (hasOnlyTitle) block.classList.add('title-only')
655  })
656}
657
658watch(
659  () => route.path,
660  () => nextTick(() => initTitleOnly()),
661  { flush: 'post' }
662)
663
664onMounted(() => {
665  if (import.meta.env.SSR) return
666
667  initTitleOnly()
668
669  // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
670  const tooltipEl = document.createElement('div')
671  tooltipEl.className = 'icon-tip-popup'
672  document.body.appendChild(tooltipEl)
673
674  const showTooltip = (e: MouseEvent) => {
675    const target = (e.target as HTMLElement).closest('.icon-tip') as
676      | HTMLElement
677      | null
678    if (!target) return
679    const tip = target.dataset.tip
680    if (!tip) return
681
682    tooltipEl.textContent = tip
683    tooltipEl.classList.add('visible')
684
685    const rect = target.getBoundingClientRect()
686    const tipWidth = tooltipEl.offsetWidth
687    const tipHeight = tooltipEl.offsetHeight
688    let left = rect.left + rect.width / 2 - tipWidth / 2
689    left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
690    const top = rect.top - tipHeight - 6
691
692    tooltipEl.style.left = `${left}px`
693    tooltipEl.style.top = `${top}px`
694  }
695
696  const hideTooltip = () => {
697    tooltipEl.classList.remove('visible')
698  }
699
700  document.addEventListener('mouseover', showTooltip)
701  document.addEventListener('mouseout', hideTooltip)
702  document.addEventListener('scroll', hideTooltip, true)
703
704  const onCaptureClick = (e: MouseEvent) => {
705    if (!e.isTrusted) return
706    const link = (e.target as HTMLElement).closest<HTMLAnchorElement>('a[href]')
707    if (!link) return
708    const raw = link.getAttribute('href') ?? ''
709
710    // ── Tab link: #tab-name or already-rewritten /path?tabs=name ──────────
711    const tabFromHash = raw.startsWith('#' + TAB_LINK_MARKER)
712      ? raw.slice(1 + TAB_LINK_MARKER.length)
713      : null
714    let tabFromQuery: string | null = null
715    if (
716      !e.defaultPrevented &&
717      !tabFromHash &&
718      raw.includes(`?${TAB_QUERY_PARAM}=`) &&
719      !raw.includes('#')
720    ) {
721      try {
722        const url = new URL(raw, window.location.href)
723        const samePage = url.origin === window.location.origin &&
724          url.pathname === window.location.pathname
725        tabFromQuery = samePage
726          ? url.searchParams.get(TAB_QUERY_PARAM)
727          : null
728      } catch {
729        tabFromQuery = null
730      }
731    }
732    const tabName = tabFromHash ?? tabFromQuery
733
734    if (tabName) {
735      e.preventDefault()
736      e.stopImmediatePropagation()
737      window.history.pushState(null, '', buildUrlWithTabs([tabName]))
738      rewriteAnchorLinks()
739      void (async () => {
740        const tabs = await selectTabsByPath([tabName])
741        if (tabs) scrollToElement(getSelectedTabScrollTarget(tabs), false)
742      })()
743      return
744    }
745
746    // ── Plain heading link: #name or already-rewritten /path#name ─────────
747    // Only intercept when ?tabs= is present — otherwise let the router handle normally.
748    if (!new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)) {
749      return
750    }
751
752    let hash: string | null = null
753    if (raw.startsWith('#') && raw.length > 1) {
754      hash = raw.slice(1)
755    } else if (raw.startsWith(window.location.pathname + '#')) {
756      hash = raw.slice(window.location.pathname.length + 1)
757    }
758    if (!hash) return
759
760    e.preventDefault()
761    e.stopImmediatePropagation()
762    window.history.pushState(null, '', `${window.location.pathname}#${hash}`)
763    rewriteAnchorLinks()
764    void tryOpenAnchoredContent()
765  }
766
767  document.addEventListener('click', onCaptureClick, { capture: true })
768
769  useEventListener(document, 'click', (e: MouseEvent) => {
770    if (!e.isTrusted) return
771    queueTabQueryUpdateForSelection(e.target)
772  })
773
774  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
775    if (!e.isTrusted || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) {
776      return
777    }
778
779    queueTabQueryUpdateForSelection(e.target)
780  })
781
782  onUnmounted(() => {
783    document.removeEventListener('click', onCaptureClick, { capture: true })
784    document.removeEventListener('mouseover', showTooltip)
785    document.removeEventListener('mouseout', hideTooltip)
786    document.removeEventListener('scroll', hideTooltip, true)
787    tooltipEl.remove()
788  })
789
790  // Arrow key scrolling + Escape close for sidebars and content
791  let activeScrollTarget: HTMLElement | Window = window
792
793  useEventListener(document, 'pointerdown', (e: PointerEvent) => {
794    const el = e.target as HTMLElement
795    if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
796      activeScrollTarget = sidebarRef.value
797    } else if (el.closest('.VPSidebar')) {
798      activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
799    } else {
800      activeScrollTarget = window
801    }
802  })
803
804  const pxPerFrame = 18
805  let scrollDirection = 0
806  let scrollRaf = 0
807
808  function tickScroll() {
809    if (!scrollDirection) return
810    activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
811    scrollRaf = requestAnimationFrame(tickScroll)
812  }
813
814  function stopScroll() {
815    scrollDirection = 0
816    cancelAnimationFrame(scrollRaf)
817  }
818
819  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
820    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
821      return
822    }
823
824    if (e.key === 'Escape') {
825      if (homeSidebarOpen.value) homeSidebarOpen.value = false
826      return
827    }
828
829    e.preventDefault()
830    const dir = e.key === 'ArrowDown' ? 1 : -1
831    if (scrollDirection === dir) return
832    scrollDirection = dir
833    cancelAnimationFrame(scrollRaf)
834    scrollRaf = requestAnimationFrame(tickScroll)
835  })
836
837  useEventListener(document, 'keyup', (e: KeyboardEvent) => {
838    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
839  })
840
841  onUnmounted(stopScroll)
842
843  // Close home NavScreen on outside click
844  useEventListener(document, 'click', (e: Event) => {
845    if (!isHome.value) return
846    const screen = document.getElementById('VPNavScreen')
847    if (!screen) return
848    const hamburger = document.querySelector('.VPNavBarHamburger')
849    if (
850      screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
851    ) return
852    requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
853  })
854
855  // Storage changed in other documents.
856  useEventListener(window, 'storage', () => {
857    reloadTakodachi()
858  })
859
860  // Storage changed in the same document.
861  useEventListener(window, customStorageEventName, () => {
862    reloadTakodachi()
863  })
864
865  reloadTakodachi()
866})
867
868onUnmounted(() => {
869  outlineFollowObserver?.disconnect()
870  cancelAnimationFrame(outlineFollowRaf)
871  takodachiDisable.value && takodachiDisable.value()
872})
873</script>
874
875<template>
876  <Layout>
877    <template #layout-top>
878      <img
879        id="takodachi"
880        ref="takodachiRef"
881        src="/takodachi.webp"
882        alt="Takodachi"
883        class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
884        :style="{
885          left: `${position.x}px`,
886          top: `${position.y}px`
887        }"
888      />
889      <!-- Home sidebar menu -->
890      <template v-if="isHome">
891        <Transition name="home-fade">
892          <div
893            v-if="homeSidebarOpen"
894            class="home-sidebar-backdrop"
895            @click="homeSidebarOpen = false"
896          />
897        </Transition>
898        <Transition name="home-slide" @after-enter="onSidebarEnter">
899          <aside
900            v-if="homeSidebarOpen"
901            ref="sidebarRef"
902            class="home-sidebar"
903            tabindex="-1"
904            @click.stop
905          >
906            <div class="home-sidebar-header">
907              <a href="/" class="home-sidebar-logo">
908                <img
909                  v-if="logoSrc"
910                  :src="logoSrc"
911                  class="home-sidebar-logo-img"
912                  alt="Logo"
913                />
914                <span>{{ theme.siteTitle ?? site.title }}</span>
915              </a>
916            </div>
917            <nav id="VPSidebarNav" class="home-sidebar-nav">
918              <VPSidebarGroup :items="homeSidebarGroups" />
919              <SidebarCard />
920            </nav>
921          </aside>
922        </Transition>
923      </template>
924    </template>
925    <template #doc-before>
926      <!-- Breadcrumb Navigation -->
927      <nav
928        v-if="breadcrumbs.length > 0"
929        class="breadcrumb mb-6 text-sm text-text-2"
930        aria-label="Breadcrumb"
931      >
932        <ol class="flex flex-wrap items-center gap-2">
933          <li>
934            <a href="/" class="hover:text-primary transition-colors">
935              <span class="i-lucide:home"></span>
936            </a>
937          </li>
938          <li
939            v-for="(crumb, index) in breadcrumbs"
940            :key="crumb.link || index"
941            class="flex items-center gap-2"
942          >
943            <span
944              class="i-lucide:chevron-right text-text-3 flex-shrink-0"
945            ></span>
946            <span
947              v-if="index === breadcrumbs.length - 1"
948              v-html="crumb.text"
949              class="font-medium text-text-1 break-words"
950            ></span>
951            <a
952              v-else
953              :href="crumb.link"
954              v-html="crumb.text"
955              class="hover:text-primary transition-colors break-words"
956            ></a>
957          </li>
958        </ol>
959      </nav>
960    </template>
961    <template #not-found>
962      <NotFoundComponent />
963    </template>
964    <template #sidebar-nav-after>
965      <SidebarCard />
966    </template>
967    <template #home-hero-info-before>
968      <AnnouncementPill />
969    </template>
970    <template #nav-bar-content-after>
971      <NolebaseEnhancedReadabilitiesMenu />
972    </template>
973    <template #nav-screen-content-before>
974      <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
975        <VPSidebarGroup :items="homeSidebarGroups" />
976      </nav>
977    </template>
978    <template #nav-screen-content-after>
979      <NolebaseEnhancedReadabilitiesScreenMenu />
980    </template>
981
982    <template #nav-bar-title-before>
983      <span
984        v-if="isHome"
985        class="home-menu-btn"
986        role="button"
987        tabindex="0"
988        aria-label="Menu"
989        @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
990        @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
991      >
992        <span class="vpi-align-left home-menu-icon" />
993      </span>
994    </template>
995  </Layout>
996</template>