docs/.vitepress/theme/Layout.vue

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

1451 lines · 45247 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  useEventListener,
  11  useStorage,
  12  useThrottleFn
  13} from '@vueuse/core'
  14import { getScrollOffset, useData, useRoute } from 'vitepress'
  15import type { DefaultTheme as Theme } from 'vitepress'
  16import VPSidebarGroup from 'vitepress/dist/client/theme-default/components/VPSidebarGroup.vue'
  17import { getSidebarGroups } from 'vitepress/dist/client/theme-default/support/sidebar'
  18import DefaultTheme from 'vitepress/theme'
  19import {
  20  computed,
  21  nextTick,
  22  onMounted,
  23  onUnmounted,
  24  ref,
  25  watch,
  26  watchEffect
  27} from 'vue'
  28import { sidebar } from '../configs/constants'
  29import { useBookmarks, BOOKMARK_CHANGE_EVENT } from './composables/useBookmarks'
  30import AnnouncementPill from './components/AnnouncementPill.vue'
  31import SiteFooter from './components/SiteFooter.vue'
  32import NotFoundComponent from './components/NotFound.vue'
  33import { NolebaseEnhancedReadabilitiesScreenMenu } from './components/settings'
  34import NavActions from './components/NavActions.vue'
  35import SidebarCard from './components/SidebarCard.vue'
  36import { AccentBgStorageKey, AccentBgStrengthStorageKey, AccentColorStorageKey } from './constants'
  37import { useEffects } from './composables/useEffects'
  38import { applyFavicons, removeFavicons, useFavicons } from './composables/useFavicons'
  39
  40const route = useRoute()
  41const { frontmatter, isDark, site, theme } = useData()
  42const { isBookmarked, toggle: bookmarkToggle } = useBookmarks()
  43const { Layout } = DefaultTheme
  44
  45// Home sidebar menu
  46const isHome = computed(() => frontmatter.value.layout === 'home')
  47const homeSidebarOpen = ref(false)
  48const sidebarRef = ref<HTMLElement | null>(null)
  49const homeSidebarGroups = getSidebarGroups(sidebar as any)
  50const logoSrc = computed(() =>
  51  typeof theme.value.logo === 'string'
  52    ? theme.value.logo
  53    : theme.value.logo?.src
  54)
  55
  56watch(() => route.path, () => {
  57  homeSidebarOpen.value = false
  58})
  59
  60let searchNavigated = false
  61let searchQuery = ''
  62
  63if (!import.meta.env.SSR) {
  64  useEventListener(window, 'search-nav', (event) => {
  65    searchNavigated = true
  66    searchQuery = event instanceof CustomEvent &&
  67        typeof event.detail?.query === 'string'
  68      ? event.detail.query
  69      : ''
  70  })
  71}
  72
  73const nextFrame = () =>
  74  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
  75
  76const getSearchTerms = (query: string) =>
  77  query
  78    .toLowerCase()
  79    .split(/\s+/)
  80    .map((term) => term.trim())
  81    .filter(Boolean)
  82
  83const getTargetByHash = (hash: string) => {
  84  const ids = [hash]
  85  try {
  86    const decoded = decodeURIComponent(hash)
  87    if (decoded !== hash) ids.unshift(decoded)
  88  } catch {
  89    /* keep the raw hash */
  90  }
  91
  92  for (const id of ids) {
  93    const target = document.getElementById(id)
  94    if (target) return target
  95  }
  96}
  97
  98const getScrollTargetForAnchor = (target: HTMLElement) => {
  99  if (target.classList.contains('tab-search-heading')) {
 100    return target.closest<HTMLElement>('.plugin-tabs') ?? target
 101  }
 102
 103  return target
 104}
 105
 106const TAB_QUERY_PARAM = 't'
 107const COLLAPSIBLE_QUERY_PARAM = 'c'
 108
 109const getRequestedAnchorPath = (param: string) => {
 110  const value = new URLSearchParams(window.location.search).get(param)
 111  return value
 112    ?.split(',')
 113    .map((anchor) => anchor.trim())
 114    .filter(Boolean) ?? []
 115}
 116
 117const getRequestedTabPath = () => getRequestedAnchorPath(TAB_QUERY_PARAM)
 118const getRequestedCollapsiblePath = () =>
 119  getRequestedAnchorPath(COLLAPSIBLE_QUERY_PARAM)
 120
 121const encodeAnchorList = (anchors: string[]) =>
 122  anchors.map((anchor) => encodeURIComponent(anchor)).join(',')
 123
 124const buildUrl = (
 125  options: { tabs?: string[]; collapsibles?: string[]; hash?: string } = {}
 126) => {
 127  const params = new URLSearchParams(window.location.search)
 128  const currentTabs = params.get(TAB_QUERY_PARAM)
 129  const currentCollapsibles = params.get(COLLAPSIBLE_QUERY_PARAM)
 130  params.delete(TAB_QUERY_PARAM)
 131  params.delete(COLLAPSIBLE_QUERY_PARAM)
 132
 133  const tabs = options.tabs ??
 134    (currentTabs ? currentTabs.split(',').filter(Boolean) : [])
 135  const collapsibles = options.collapsibles ??
 136    (currentCollapsibles ? currentCollapsibles.split(',').filter(Boolean) : [])
 137
 138  const queryParts = [
 139    params.toString(),
 140    tabs.length ? `${TAB_QUERY_PARAM}=${encodeAnchorList(tabs)}` : '',
 141    collapsibles.length
 142      ? `${COLLAPSIBLE_QUERY_PARAM}=${encodeAnchorList(collapsibles)}`
 143      : ''
 144  ].filter(Boolean)
 145
 146  const hash = options.hash ?? ''
 147  return `${window.location.pathname}${
 148    queryParts.length ? `?${queryParts.join('&')}` : ''
 149  }${hash ? `#${encodeURIComponent(hash)}` : ''}`
 150}
 151
 152const buildUrlWithTabs = (tabs: string[], hash = '') => buildUrl({ tabs, hash })
 153
 154const getSelectedTabAnchor = (tabs: HTMLElement) =>
 155  tabs.querySelector<HTMLButtonElement>(
 156    '.plugin-tabs--tab[aria-selected="true"][data-tab-anchor]'
 157  )?.dataset.tabAnchor
 158
 159const getPanelForTabButton = (button: HTMLButtonElement) => {
 160  const panelId = button.getAttribute('aria-controls')
 161  return panelId ? document.getElementById(panelId) : undefined
 162}
 163
 164const getTabPathForGroup = (tabs: HTMLElement) => {
 165  const groups: HTMLElement[] = []
 166  let currentTabs: HTMLElement | null = tabs
 167
 168  while (currentTabs) {
 169    groups.unshift(currentTabs)
 170    const parentPanel = currentTabs.parentElement?.closest<HTMLElement>(
 171      '.plugin-tabs--content[data-tab-anchor]'
 172    )
 173    currentTabs = parentPanel?.closest<HTMLElement>('.plugin-tabs') ?? null
 174  }
 175
 176  return groups
 177    .map((group) => getSelectedTabAnchor(group))
 178    .filter((tab): tab is string => Boolean(tab))
 179}
 180
 181const updateQueryForSelectedTab = async (tabs: HTMLElement) => {
 182  await nextTick()
 183  await nextFrame()
 184
 185  const tabPath = getTabPathForGroup(tabs)
 186  if (!tabPath.length) return
 187
 188  const collapsibles = getOpenCollapsiblePath(tabs)
 189
 190  const nextUrl = buildUrl({ tabs: tabPath, collapsibles })
 191  const currentUrl =
 192    `${window.location.pathname}${window.location.search}${window.location.hash}`
 193  if (nextUrl === currentUrl) return
 194
 195  window.history.pushState(null, '', nextUrl)
 196  rewriteAnchorLinks()
 197}
 198
 199const queueTabQueryUpdateForSelection = (target: EventTarget | null) => {
 200  if (!(target instanceof HTMLElement)) return
 201
 202  const button = target.closest<HTMLButtonElement>(
 203    '.plugin-tabs--tab[role="tab"]'
 204  )
 205  const tabs = button?.closest<HTMLElement>('.plugin-tabs')
 206  if (tabs) void updateQueryForSelectedTab(tabs)
 207}
 208
 209const COLLAPSIBLE_SELECTOR = 'details[data-collapsible-anchor]'
 210
 211const getOpenCollapsiblePath = (details: HTMLElement) => {
 212  const path: string[] = []
 213  let el: HTMLElement | null = details
 214
 215  while (el) {
 216    const current: HTMLElement | null = el.closest(COLLAPSIBLE_SELECTOR)
 217    if (!current) break
 218
 219    if ((current as HTMLDetailsElement).open) {
 220      const anchor = current.dataset.collapsibleAnchor
 221      if (anchor) path.unshift(anchor)
 222    }
 223
 224    el = current.parentElement
 225  }
 226
 227  return path
 228}
 229
 230const getEnclosingTabPath = (el: HTMLElement) => {
 231  const panel = el.closest<HTMLElement>(
 232    '.plugin-tabs--content[data-tab-anchor]'
 233  )
 234  const tabs = panel?.closest<HTMLElement>('.plugin-tabs')
 235  return tabs ? getTabPathForGroup(tabs) : []
 236}
 237
 238const updateQueryForCollapsible = async (details: HTMLElement) => {
 239  await nextTick()
 240  await nextFrame()
 241
 242  const collapsiblePath = getOpenCollapsiblePath(details)
 243  const tabPath = getEnclosingTabPath(details)
 244
 245  const nextUrl = buildUrl({
 246    tabs: tabPath.length ? tabPath : [],
 247    collapsibles: collapsiblePath
 248  })
 249  const currentUrl =
 250    `${window.location.pathname}${window.location.search}${window.location.hash}`
 251  if (nextUrl === currentUrl) return
 252
 253  window.history.pushState(null, '', nextUrl)
 254  rewriteAnchorLinks()
 255}
 256
 257const queueCollapsibleQueryUpdate = (target: EventTarget | null) => {
 258  if (!(target instanceof HTMLElement)) return
 259
 260  const summary = target.closest<HTMLElement>('summary')
 261  const details = summary?.parentElement
 262  if (details instanceof HTMLElement && details.matches(COLLAPSIBLE_SELECTOR)) {
 263    void updateQueryForCollapsible(details)
 264  }
 265}
 266
 267const selectCollapsiblesByPath = async (collapsiblePath: string[]) => {
 268  let root: ParentNode = document
 269  let opened: HTMLElement | undefined
 270
 271  for (const anchor of collapsiblePath) {
 272    const details = root.querySelector<HTMLDetailsElement>(
 273      `details[data-collapsible-anchor="${CSS.escape(anchor)}"]`
 274    )
 275    if (!details) return opened
 276
 277    opened = details
 278    if (!details.open) {
 279      details.open = true
 280      await nextTick()
 281      await nextFrame()
 282    }
 283
 284    root = details
 285  }
 286
 287  return opened
 288}
 289
 290const TAB_LINK_MARKER = 'tab-'
 291
 292const rewriteAnchorLinks = () => {
 293  const origin = window.location.origin
 294  const pathname = window.location.pathname
 295
 296  document
 297    .querySelectorAll<HTMLAnchorElement>('.VPDoc .vp-doc a[href]')
 298    .forEach((link) => {
 299      // Accept either the original `#…` form or a previously-rewritten absolute URL.
 300      const raw = link.getAttribute('href') ?? ''
 301      let fragment: string | null = null
 302      if (raw.startsWith('#') && raw.length > 1) {
 303        fragment = raw.slice(1)
 304      } else if (raw.startsWith(origin + pathname + '#')) {
 305        fragment = raw.slice((origin + pathname + '#').length)
 306      } else if (raw.startsWith(origin + pathname + '?')) {
 307        // Already rewritten as a tab link — re-derive the tab name and re-stamp.
 308        const qs = raw.slice((origin + pathname + '?').length).split('#')[0]
 309        const tabName = new URLSearchParams(qs).get(TAB_QUERY_PARAM)
 310        if (tabName) {
 311          const href = `${origin}${pathname}?${TAB_QUERY_PARAM}=${
 312            encodeURIComponent(tabName)
 313          }`
 314          if (link.getAttribute('href') !== href) {
 315            link.setAttribute('href', href)
 316          }
 317        }
 318        return
 319      } else {
 320        return
 321      }
 322
 323      const isTabLink = fragment.startsWith(TAB_LINK_MARKER)
 324      const name = (isTabLink
 325        ? fragment.slice(TAB_LINK_MARKER.length)
 326        : fragment).trim()
 327      if (!name) return
 328
 329      // Use absolute URLs so the browser's Copy Link has nothing to merge with
 330      // the current ?tabs= query.
 331      const href = isTabLink
 332        ? `${origin}${pathname}?${TAB_QUERY_PARAM}=${encodeURIComponent(name)}`
 333        : `${origin}${pathname}#${name}`
 334
 335      if (link.getAttribute('href') !== href) link.setAttribute('href', href)
 336    })
 337}
 338
 339const selectTabsByPath = async (tabPath: string[]) => {
 340  let root: ParentNode = document
 341  let selectedTabs: HTMLElement | undefined
 342
 343  for (const anchor of tabPath) {
 344    const button = root.querySelector<HTMLButtonElement>(
 345      `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(anchor)}"]`
 346    )
 347    if (!button) return selectedTabs
 348
 349    const tabs = button.closest<HTMLElement>('.plugin-tabs')
 350    if (!tabs) return selectedTabs
 351
 352    selectedTabs = tabs
 353    if (button.getAttribute('aria-selected') !== 'true') {
 354      button.click()
 355      await nextTick()
 356      await nextFrame()
 357    }
 358
 359    root = getPanelForTabButton(button) ?? tabs
 360  }
 361
 362  return selectedTabs
 363}
 364
 365const selectLegacyTabHash = async (hash: string) => {
 366  const button = document.querySelector<HTMLButtonElement>(
 367    `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(hash)}"]`
 368  )
 369  if (!button) return
 370
 371  if (button.getAttribute('aria-selected') !== 'true') {
 372    button.click()
 373    await nextTick()
 374    await nextFrame()
 375  }
 376
 377  const tabs = button.closest<HTMLElement>('.plugin-tabs')
 378  if (tabs) {
 379    window.history.replaceState(null, '', buildUrlWithTabs([hash]))
 380  }
 381  return tabs
 382}
 383
 384const getSelectedTabScrollTarget = (tabs: HTMLElement) => {
 385  const selectedTab = tabs.querySelector<HTMLButtonElement>(
 386    '.plugin-tabs--tab[aria-selected="true"]'
 387  )
 388  return selectedTab ? getPanelForTabButton(selectedTab) ?? tabs : tabs
 389}
 390
 391const scrollToElement = (target: HTMLElement, smooth = true) => {
 392  requestAnimationFrame(() => {
 393    requestAnimationFrame(() => {
 394      const navBar = document.querySelector<HTMLElement>('.VPNavBar')
 395      const navOffset = navBar ? navBar.offsetHeight : 0
 396      window.scrollTo({
 397        top: target.getBoundingClientRect().top + window.scrollY - navOffset,
 398        behavior: smooth &&
 399            !window.matchMedia('(prefers-reduced-motion: reduce)').matches
 400          ? 'smooth'
 401          : 'auto'
 402      })
 403      target.setAttribute('tabindex', '-1')
 404      target.focus({ preventScroll: true })
 405    })
 406  })
 407}
 408
 409const openCollapsibles = async (target: HTMLElement) => {
 410  const activeTarget = target
 411  let scrollTarget = getScrollTargetForAnchor(activeTarget)
 412  let el: HTMLElement | null = activeTarget
 413
 414  while ((el = el.closest('details'))) {
 415    el.open = true
 416    scrollTarget = el
 417    el = el.parentElement
 418  }
 419
 420  const tagName = activeTarget.tagName
 421  if (tagName.length === 2 && tagName[0] === 'H') {
 422    const level = +tagName[1]
 423    if (level >= 1 && level <= 6) {
 424      const terms = getSearchTerms(searchQuery)
 425      const detailsContainsTerms = (d: HTMLElement) => {
 426        if (!terms.length) return false
 427        const text = (d.textContent ?? '').toLowerCase()
 428        return terms.every((term) => text.includes(term))
 429      }
 430
 431      let sibling = activeTarget.nextElementSibling
 432
 433      while (sibling) {
 434        const siblingTag = sibling.tagName
 435        if (
 436          siblingTag.length === 2 && siblingTag[0] === 'H' &&
 437          +siblingTag[1] <= level
 438        ) break
 439
 440        if (siblingTag === 'DETAILS') {
 441          if (detailsContainsTerms(sibling as HTMLElement)) {
 442            ;(sibling as HTMLDetailsElement).open = true
 443            if (scrollTarget === activeTarget) {
 444              scrollTarget = sibling as HTMLElement
 445            }
 446          }
 447        }
 448
 449        const nested = sibling.getElementsByTagName('details')
 450        for (let i = 0, len = nested.length; i < len; i++) {
 451          if (detailsContainsTerms(nested[i])) {
 452            nested[i].open = true
 453            if (scrollTarget === activeTarget) scrollTarget = nested[i]
 454          }
 455        }
 456
 457        sibling = sibling.nextElementSibling
 458      }
 459    }
 460  }
 461
 462  await nextTick()
 463  await nextFrame()
 464
 465  scrollToElement(scrollTarget)
 466}
 467
 468const resetSearchNavigation = () => {
 469  searchNavigated = false
 470  searchQuery = ''
 471}
 472
 473const tryOpenAnchoredContent = async () => {
 474  await nextTick()
 475  await nextFrame()
 476
 477  const requestedTabs = getRequestedTabPath()
 478  const selectedTabs = requestedTabs.length
 479    ? await selectTabsByPath(requestedTabs)
 480    : undefined
 481  const requestedCollapsibles = getRequestedCollapsiblePath()
 482  const openedCollapsible = requestedCollapsibles.length
 483    ? await selectCollapsiblesByPath(requestedCollapsibles)
 484    : undefined
 485  const hash = window.location.hash.slice(1)
 486
 487  if (!hash) {
 488    resetSearchNavigation()
 489    if (openedCollapsible) {
 490      scrollToElement(openedCollapsible, false)
 491    } else if (selectedTabs) {
 492      scrollToElement(getSelectedTabScrollTarget(selectedTabs), false)
 493    }
 494    return
 495  }
 496
 497  let target = getTargetByHash(hash)
 498
 499  if (!target && !requestedTabs.length) {
 500    const legacyTabs = await selectLegacyTabHash(hash)
 501    if (legacyTabs) {
 502      resetSearchNavigation()
 503      scrollToElement(getSelectedTabScrollTarget(legacyTabs), false)
 504      return
 505    }
 506  }
 507
 508  if (!target) {
 509    if (searchNavigated) resetSearchNavigation()
 510    return
 511  }
 512
 513  if (searchNavigated) {
 514    await openCollapsibles(target)
 515    const collapsiblePath = getOpenCollapsiblePath(target)
 516    if (collapsiblePath.length) {
 517      const tabPath = getEnclosingTabPath(target)
 518      window.history.replaceState(
 519        null,
 520        '',
 521        buildUrl({
 522          tabs: tabPath.length ? tabPath : undefined,
 523          collapsibles: collapsiblePath
 524        })
 525      )
 526      rewriteAnchorLinks()
 527    }
 528    resetSearchNavigation()
 529    return
 530  }
 531
 532  const isTabRelatedTarget = target.classList.contains('tab-search-heading') ||
 533    Boolean(target.closest('.plugin-tabs'))
 534
 535  if (
 536    !isTabRelatedTarget &&
 537    new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)
 538  ) {
 539    window.history.replaceState(null, '', buildUrlWithTabs([], hash))
 540    scrollToElement(getScrollTargetForAnchor(target), false)
 541    return
 542  }
 543
 544  if (target.classList.contains('tab-search-heading')) {
 545    const tabs = target.closest<HTMLElement>('.plugin-tabs')
 546    if (tabs) {
 547      window.history.replaceState(
 548        null,
 549        '',
 550        buildUrlWithTabs(getTabPathForGroup(tabs))
 551      )
 552    }
 553  }
 554
 555  if (
 556    selectedTabs ||
 557    target.classList.contains('tab-search-heading')
 558  ) {
 559    scrollToElement(getScrollTargetForAnchor(target), false)
 560  }
 561}
 562
 563const rewriteAnchorLinksDeferred = () => nextTick(() => rewriteAnchorLinks())
 564
 565let outlineFollowObserver: MutationObserver | null = null
 566let outlineFollowRaf = 0
 567
 568const syncMobileOutlineActive = () => {
 569  const dropdownLinks = Array.from(
 570    document.querySelectorAll<HTMLAnchorElement>(
 571      '.VPLocalNavOutlineDropdown .outline a.outline-link'
 572    )
 573  )
 574  if (!dropdownLinks.length) return
 575
 576  const scrollY = window.scrollY
 577  const isBottom =
 578    Math.abs(scrollY + window.innerHeight - document.body.offsetHeight) < 1
 579
 580  const entries = dropdownLinks
 581    .map(link => {
 582      const href = link.getAttribute('href') ?? ''
 583      const id = href.startsWith('#') ? decodeURIComponent(href.slice(1)) : ''
 584      const el = id ? document.getElementById(id) : null
 585      return el ? { href, top: el.getBoundingClientRect().top + scrollY } : null
 586    })
 587    .filter((e): e is { href: string; top: number } => e !== null)
 588    .sort((a, b) => a.top - b.top)
 589
 590  let activeHref: string | null = null
 591  if (entries.length && scrollY >= 1) {
 592    if (isBottom) {
 593      activeHref = entries[entries.length - 1].href
 594    } else {
 595      for (const { href, top } of entries) {
 596        if (top > scrollY + getScrollOffset() + 4) break
 597        activeHref = href
 598      }
 599    }
 600  }
 601
 602  dropdownLinks.forEach(link => {
 603    link.classList.toggle('active', link.getAttribute('href') === activeHref)
 604  })
 605}
 606
 607let mobileOutlineScrollRaf = 0
 608const onMobileOutlineScroll = () => {
 609  cancelAnimationFrame(mobileOutlineScrollRaf)
 610  mobileOutlineScrollRaf = requestAnimationFrame(syncMobileOutlineActive)
 611}
 612
 613const followActiveOutlineLink = () => {
 614  cancelAnimationFrame(outlineFollowRaf)
 615
 616  outlineFollowRaf = requestAnimationFrame(() => {
 617    const activeLink = document.querySelector<HTMLElement>(
 618      '.VPDocAsideOutline a.outline-link.active'
 619    )
 620    const scroller = activeLink?.closest<HTMLElement>('.aside-container')
 621    if (!activeLink || !scroller) return
 622
 623    const linkRect = activeLink.getBoundingClientRect()
 624    const scrollerRect = scroller.getBoundingClientRect()
 625    const margin = 32
 626
 627    if (linkRect.top < scrollerRect.top + margin) {
 628      scroller.scrollTop += linkRect.top - scrollerRect.top - margin
 629    } else if (linkRect.bottom > scrollerRect.bottom - margin) {
 630      scroller.scrollTop += linkRect.bottom - scrollerRect.bottom + margin
 631    }
 632  })
 633}
 634
 635const setupOutlineFollow = () => {
 636  outlineFollowObserver?.disconnect()
 637  outlineFollowObserver = null
 638
 639  const outline = document.querySelector('.VPDocAsideOutline')
 640  if (!outline) return
 641
 642  outlineFollowObserver = new MutationObserver((mutations) => {
 643    if (
 644      mutations.some((mutation) =>
 645        mutation.type === 'childList' ||
 646        (mutation.target instanceof HTMLElement &&
 647          mutation.target.matches('a.outline-link'))
 648      )
 649    ) {
 650      followActiveOutlineLink()
 651    }
 652  })
 653
 654  outlineFollowObserver.observe(outline, {
 655    attributes: true,
 656    attributeFilter: ['class'],
 657    childList: true,
 658    subtree: true
 659  })
 660  followActiveOutlineLink()
 661}
 662
 663const BOOKMARK_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/></svg>`
 664
 665function syncTocBookmarkStates() {
 666  const path = route.path
 667  document.querySelectorAll<HTMLElement>('.toc-bookmark-btn').forEach(btn => {
 668    const anchor = btn.dataset.anchor ?? ''
 669    btn.classList.toggle('is-bookmarked', isBookmarked(anchor, path))
 670  })
 671}
 672
 673function addBookmarkBtnToLi(li: HTMLElement, path: string) {
 674  if (li.querySelector('.toc-bookmark-btn')) return
 675
 676  const link = li.querySelector<HTMLAnchorElement>(':scope > .outline-link')
 677  if (!link) return
 678
 679  const hrefAttr = link.getAttribute('href') ?? ''
 680  const anchor = hrefAttr.startsWith('#') ? hrefAttr.slice(1) : hrefAttr
 681  const title = link.textContent?.trim() ?? ''
 682  if (!anchor || !title) return
 683
 684  const btn = document.createElement('button')
 685  btn.className = 'toc-bookmark-btn'
 686  btn.setAttribute('aria-label', `Bookmark "${title}"`)
 687  btn.dataset.anchor = anchor
 688  btn.innerHTML = BOOKMARK_SVG
 689
 690  if (isBookmarked(anchor, path)) btn.classList.add('is-bookmarked')
 691
 692  btn.addEventListener('click', (e) => {
 693    e.preventDefault()
 694    e.stopPropagation()
 695    bookmarkToggle({ anchor, title, path })
 696    btn.classList.toggle('is-bookmarked', isBookmarked(anchor, path))
 697  })
 698
 699  link.appendChild(btn)
 700}
 701
 702let tocMutationObserver: MutationObserver | null = null
 703let tocRaf = 0
 704
 705function scanTocItems(path: string) {
 706  // Desktop sidebar — VPDocOutlineItem is called with :root="true"
 707  document.querySelectorAll<HTMLElement>('.VPDocOutlineItem.root > li').forEach(li => addBookmarkBtnToLi(li, path))
 708  // Mobile dropdown — VPDocOutlineItem is called without root prop, so the ul gets class "nested"
 709  document.querySelectorAll<HTMLElement>('.VPLocalNavOutlineDropdown .outline > .VPDocOutlineItem > li').forEach(li => addBookmarkBtnToLi(li, path))
 710}
 711
 712function setupTocBookmarks() {
 713  const path = route.path
 714  document.querySelectorAll<HTMLElement>('.toc-bookmark-btn').forEach(btn => btn.remove())
 715  scanTocItems(path)
 716
 717  // Mobile dropdown items are v-if rendered on open — watch for them being added
 718  tocMutationObserver?.disconnect()
 719  tocMutationObserver = new MutationObserver(() => {
 720    cancelAnimationFrame(tocRaf)
 721    tocRaf = requestAnimationFrame(() => {
 722      scanTocItems(route.path)
 723      syncMobileOutlineActive()
 724    })
 725  })
 726  tocMutationObserver.observe(document.body, { childList: true, subtree: true })
 727}
 728
 729onMounted(tryOpenAnchoredContent)
 730onMounted(rewriteAnchorLinksDeferred)
 731onMounted(() => nextTick(setupOutlineFollow))
 732onMounted(() => nextTick(setupTocBookmarks))
 733onMounted(() => window.addEventListener('scroll', onMobileOutlineScroll, { passive: true }))
 734onUnmounted(() => window.removeEventListener('scroll', onMobileOutlineScroll))
 735watch(() => route.data, () => {
 736  void tryOpenAnchoredContent()
 737  rewriteAnchorLinksDeferred()
 738  nextTick(setupOutlineFollow)
 739  nextTick(setupManualCopyButtons)
 740  nextTick(setupTocBookmarks)
 741}, { flush: 'post' })
 742watch(() => route.query, () => {
 743  void tryOpenAnchoredContent()
 744  rewriteAnchorLinksDeferred()
 745}, { flush: 'post' })
 746watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
 747
 748function onSidebarEnter() {
 749  sidebarRef.value?.focus()
 750}
 751
 752interface BreadcrumbItem {
 753  text: string
 754  link?: string
 755}
 756
 757const buildBreadcrumbs = (
 758  items: Theme.SidebarItem[],
 759  currentPath: string
 760): BreadcrumbItem[] => {
 761  for (const item of items) {
 762    // Check if this item matches the current path
 763    if (item.link === currentPath) {
 764      return [
 765        {
 766          text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
 767          link: item.link
 768        }
 769      ]
 770    }
 771
 772    // Check nested items
 773    if (item.items) {
 774      const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
 775      if (nestedBreadcrumbs.length > 0) {
 776        return [
 777          {
 778            text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
 779            link: item.link
 780          },
 781          ...nestedBreadcrumbs
 782        ]
 783      }
 784    }
 785  }
 786  return []
 787}
 788
 789const breadcrumbs = computed(() => {
 790  const currentPath = route.path
 791  // @ts-expect-error
 792  return buildBreadcrumbs(sidebar, currentPath)
 793})
 794
 795const { effectsEnabled } = useEffects()
 796
 797watchEffect(() => {
 798  if (import.meta.env.SSR) return
 799
 800  // Effects are off by default; the class strips blur/transitions/scaling.
 801  document.documentElement.classList.toggle(
 802    'effects-disabled',
 803    !effectsEnabled.value
 804  )
 805})
 806
 807const { faviconsEnabled } = useFavicons()
 808
 809watch(faviconsEnabled, (enabled) => {
 810  if (import.meta.env.SSR) return
 811  if (enabled) nextTick(() => applyFavicons(document))
 812  else removeFavicons()
 813}, { immediate: true })
 814
 815watch(
 816  () => route.path,
 817  () => nextTick(() => { if (faviconsEnabled.value) applyFavicons(document) }),
 818  { flush: 'post' }
 819)
 820
 821type ShadeMap = Record<string, string>
 822type PaletteEntry = ShadeMap | { dark: ShadeMap; light: ShadeMap }
 823
 824const accentPalettes: Record<string, PaletteEntry> = {
 825  ayanami: {
 826    400: 'oklch(0.722 0.105 247.48)',
 827    500: 'oklch(0.626 0.098 247.46)',
 828    600: 'oklch(0.523 0.081 246.86)',
 829    700: 'oklch(0.43 0.066 246.75)',
 830    800: 'oklch(0.335 0.052 246.76)',
 831  },
 832  asuka: {
 833    400: 'oklch(0.740 0.210 32)',
 834    500: 'oklch(0.650 0.240 30)',
 835    600: 'oklch(0.555 0.238 28)',
 836    700: 'oklch(0.455 0.205 26)',
 837    800: 'oklch(0.370 0.165 24)',
 838  },
 839  irys: {
 840    400: 'oklch(0.716 0.188 5.18)',
 841    500: 'oklch(0.659 0.237 8.99)',
 842    600: 'oklch(0.584 0.229 10.32)',
 843    700: 'oklch(0.538 0.213 9.67)',
 844    800: 'oklch(0.475 0.187 5.94)',
 845  },
 846  inanis: {
 847    400: 'oklch(0.762 0.073 302.02)',
 848    500: 'oklch(0.663 0.102 301.22)',
 849    600: 'oklch(0.580 0.119 301.34)',
 850    700: 'oklch(0.508 0.114 301.00)',
 851    800: 'oklch(0.452 0.094 302.20)',
 852  },
 853  baelz: {
 854    400: 'oklch(0.720 0.215 22.00)',
 855    500: 'oklch(0.640 0.255 22.00)',
 856    600: 'oklch(0.555 0.268 22.00)',
 857    700: 'oklch(0.472 0.248 22.00)',
 858    800: 'oklch(0.395 0.208 22.00)',
 859  },
 860  amelia: {
 861    400: 'oklch(0.800 0.085 75.49)',
 862    500: 'oklch(0.710 0.090 72.47)',
 863    600: 'oklch(0.594 0.085 69.07)',
 864    700: 'oklch(0.496 0.078 72.12)',
 865    800: 'oklch(0.391 0.062 68.86)',
 866  },
 867  suisei: {
 868    400: 'oklch(0.827 0.096 224.60)',
 869    500: 'oklch(0.740 0.119 230.91)',
 870    600: 'oklch(0.645 0.127 236.29)',
 871    700: 'oklch(0.548 0.120 241.26)',
 872    800: 'oklch(0.451 0.106 244.63)',
 873  },
 874  miku: {
 875    400: 'oklch(0.788 0.133 184.43)',
 876    500: 'oklch(0.711 0.123 185.28)',
 877    600: 'oklch(0.607 0.104 187.31)',
 878    700: 'oklch(0.515 0.086 189.60)',
 879    800: 'oklch(0.441 0.071 190.95)',
 880  },
 881  fubuki: {
 882    dark: {
 883      400: 'oklch(0.88 0 0)',
 884      500: 'oklch(0.78 0 0)',
 885      600: 'oklch(0.68 0 0)',
 886      700: 'oklch(0.58 0 0)',
 887      800: 'oklch(0.48 0 0)',
 888    },
 889    light: {
 890      400: 'oklch(0.52 0 0)',
 891      500: 'oklch(0.42 0 0)',
 892      600: 'oklch(0.32 0 0)',
 893      700: 'oklch(0.22 0 0)',
 894      800: 'oklch(0.12 0 0)',
 895    },
 896  },
 897}
 898
 899const accentColor = useStorage(AccentColorStorageKey, 'ayanami')
 900const accentBg = useStorage(AccentBgStorageKey, false)
 901const accentBgStrength = useStorage(AccentBgStrengthStorageKey, 60)
 902
 903// Accent-tinted replacements for the neutral tokens in style.scss.
 904// Lightness matches the original hex values, so contrast is unchanged.
 905// Entries are [lightness, chroma] or [lightness, chroma, alpha].
 906type TintEntry = [number, number] | [number, number, number]
 907const accentBgTokens: Record<'dark' | 'light', Record<string, TintEntry>> = {
 908  dark: {
 909    '--vp-c-bg': [0.187, 0.024],
 910    '--vp-c-bg-alt': [0.164, 0.022],
 911    '--vp-c-bg-elv': [0.224, 0.028],
 912    '--vp-c-bg-soft': [0.224, 0.028],
 913    '--vp-c-divider': [0.26, 0.032],
 914    '--vp-c-border': [0.57, 0.02],
 915    '--vp-c-text-1': [0.915, 0.012],
 916    '--vp-c-text-2': [0.742, 0.012],
 917    '--vp-c-text-3': [0.655, 0.012],
 918    '--wk-c-menu-bg': [0.295, 0.032],
 919    '--wk-c-nav-solid-bg': [0.2, 0.024],
 920    '--nav-pill-bg': [0.205, 0.024, 0.7],
 921    '--wk-fs-header-divider': [0.44, 0.02, 0.65],
 922  },
 923  light: {
 924    '--vp-c-bg': [0.986, 0.012],
 925    '--vp-c-bg-alt': [0.958, 0.024],
 926    '--vp-c-bg-elv': [0.958, 0.024],
 927    '--vp-c-bg-soft': [0.958, 0.024],
 928    '--vp-c-divider': [0.828, 0.036],
 929    '--vp-c-border': [0.815, 0.024],
 930    '--vp-c-gutter': [0.913, 0.02],
 931    '--vp-c-text-1': [0.224, 0.016],
 932    '--vp-c-text-2': [0.309, 0.014],
 933    '--vp-c-text-3': [0.396, 0.014],
 934    '--wk-c-menu-bg': [0.928, 0.026],
 935    '--wk-c-nav-solid-bg': [0.986, 0.012],
 936    '--nav-pill-bg': [0.99, 0.01, 0.8],
 937    '--wk-fs-header-divider': [0.715, 0.02, 0.25],
 938  },
 939}
 940const accentBgTokenKeys = [...new Set([
 941  ...Object.keys(accentBgTokens.dark),
 942  ...Object.keys(accentBgTokens.light),
 943])]
 944
 945const applyAccentTheme = () => {
 946  if (import.meta.env.SSR) return
 947  const palette = accentPalettes[accentColor.value] ?? accentPalettes.ayanami
 948  const shades = 'dark' in palette
 949    ? (isDark.value ? palette.dark : palette.light)
 950    : palette
 951  const el = document.documentElement
 952  if (isDark.value) {
 953    el.style.setProperty('--vp-c-brand-1', shades['400'])
 954    el.style.setProperty('--vp-c-brand-2', shades['500'])
 955    el.style.setProperty('--vp-c-brand-3', shades['700'])
 956    el.style.setProperty('--vp-c-brand-soft', `color-mix(in srgb, ${shades['500']} 20%, transparent)`)
 957    el.style.setProperty('--vp-c-sidebar-active', `color-mix(in srgb, ${shades['500']} 15%, transparent)`)
 958  } else {
 959    el.style.setProperty('--vp-c-brand-1', shades['500'])
 960    el.style.setProperty('--vp-c-brand-2', shades['600'])
 961    el.style.setProperty('--vp-c-brand-3', shades['800'])
 962    el.style.setProperty('--vp-c-brand-soft', `color-mix(in srgb, ${shades['400']} 40%, transparent)`)
 963    el.style.setProperty('--vp-c-sidebar-active', `color-mix(in srgb, ${shades['800']} 15%, transparent)`)
 964  }
 965
 966  for (const key of accentBgTokenKeys) el.style.removeProperty(key)
 967  const userStrength = accentBg.value
 968    ? Math.min(100, Math.max(0, Number(accentBgStrength.value) || 0)) / 100
 969    : 0
 970  if (userStrength > 0) {
 971    const parsed = shades['500'].match(/oklch\(\s*[\d.]+\s+([\d.]+)\s+([\d.]+)/)
 972    if (parsed) {
 973      // Tint scales with the accent's own chroma (full tint at C >= 0.10,
 974      // grayscale accents stay gray), then with the intensity preset.
 975      const strength = Math.min(1, Number(parsed[1]) / 0.10) * userStrength * 1.5
 976      const hue = parsed[2]
 977      const tokens = accentBgTokens[isDark.value ? 'dark' : 'light']
 978      for (const [key, [l, c, alpha]] of Object.entries(tokens)) {
 979        const chroma = (c * strength).toFixed(4)
 980        const suffix = alpha === undefined ? '' : ` / ${alpha}`
 981        el.style.setProperty(key, `oklch(${l} ${chroma} ${hue}${suffix})`)
 982      }
 983    }
 984  }
 985}
 986
 987// Applying the tint restyles the whole page, so throttle rapid changes
 988// (leading + trailing: single clicks apply instantly, the last value sticks).
 989const applyAccentThemeThrottled = useThrottleFn(applyAccentTheme, 100, true)
 990
 991watch(
 992  [accentColor, isDark, accentBg, accentBgStrength],
 993  () => applyAccentThemeThrottled(),
 994  { immediate: true }
 995)
 996
 997function initTitleOnly() {
 998  document.querySelectorAll('.custom-block').forEach(block => {
 999    const children = [...block.children]
1000    const hasOnlyTitle = children.every(el =>
1001      el.classList.contains('custom-block-title')
1002    )
1003    if (hasOnlyTitle) block.classList.add('title-only')
1004  })
1005}
1006
1007// Wrap bare tables in their own scroll container so they scroll independently of sibling content.
1008function wrapTablesInRoot(root: ParentNode) {
1009  root.querySelectorAll<HTMLTableElement>('table:not(.scrape-table)').forEach(table => {
1010    if (table.parentElement?.classList.contains('table-scroll')) return
1011    const wrapper = document.createElement('div')
1012    wrapper.className = 'table-scroll'
1013    table.replaceWith(wrapper)
1014    wrapper.appendChild(table)
1015  })
1016}
1017
1018function initCopyButtonsInRoot(root: ParentNode) {
1019  root.querySelectorAll<HTMLTableElement>('table').forEach(table => {
1020    const headers = table.querySelectorAll<HTMLTableCellElement>('thead th')
1021    let manualColIndex = -1
1022    headers.forEach((th, i) => {
1023      if (th.textContent?.trim() === 'Manual') manualColIndex = i
1024    })
1025    if (manualColIndex === -1) return
1026
1027    // Track how many more rows each column is occupied by a rowspan from above
1028    const colOccupied: number[] = []
1029
1030    table.querySelectorAll<HTMLTableRowElement>('tbody tr').forEach(row => {
1031      const cells = Array.from(row.querySelectorAll('td'))
1032      let cellIdx = 0
1033      let col = 0
1034      let manualCell: HTMLTableCellElement | null = null
1035
1036      while (col <= manualColIndex) {
1037        // Column occupied by a rowspan from a previous row — skip it
1038        if ((colOccupied[col] ?? 0) > 0) {
1039          colOccupied[col]--
1040          col++
1041          continue
1042        }
1043
1044        if (cellIdx >= cells.length) break
1045        const cell = cells[cellIdx++]
1046        const colspan = cell.colSpan || 1
1047        const rowspan = cell.rowSpan || 1
1048
1049        // Register future occupation for rowspan > 1
1050        if (rowspan > 1) {
1051          for (let c = col; c < col + colspan; c++) {
1052            colOccupied[c] = (colOccupied[c] ?? 0) + (rowspan - 1)
1053          }
1054        }
1055
1056        if (col <= manualColIndex && col + colspan > manualColIndex) {
1057          manualCell = cell
1058        }
1059
1060        col += colspan
1061      }
1062
1063      if (!manualCell || manualCell.querySelector('.manual-copy-btn')) return
1064
1065      const link = manualCell.querySelector<HTMLAnchorElement>('a[href]')
1066      if (!link) return
1067      const url = link.getAttribute('href')!
1068
1069      const btn = document.createElement('button')
1070      btn.className = 'manual-copy-btn'
1071      btn.title = 'Copy URL'
1072      const icon = document.createElement('span')
1073      icon.className = 'i-lucide:copy'
1074      btn.appendChild(icon)
1075
1076      btn.addEventListener('click', async (e) => {
1077        e.preventDefault()
1078        try {
1079          await navigator.clipboard.writeText(url)
1080          icon.className = 'i-lucide:check'
1081          btn.classList.add('copied')
1082          setTimeout(() => {
1083            icon.className = 'i-lucide:copy'
1084            btn.classList.remove('copied')
1085          }, 2000)
1086        } catch {}
1087      })
1088
1089      manualCell.classList.add('has-manual-copy')
1090      manualCell.appendChild(btn)
1091    })
1092  })
1093}
1094
1095let copyButtonObserver: MutationObserver | null = null
1096
1097function setupManualCopyButtons() {
1098  wrapTablesInRoot(document)
1099  initCopyButtonsInRoot(document)
1100
1101  copyButtonObserver?.disconnect()
1102  copyButtonObserver = new MutationObserver((mutations) => {
1103    for (const mutation of mutations) {
1104      for (const node of mutation.addedNodes) {
1105        if (!(node instanceof HTMLElement)) continue
1106        if (node.classList.contains('plugin-tabs--content')) {
1107          wrapTablesInRoot(node)
1108          initCopyButtonsInRoot(node)
1109          if (faviconsEnabled.value) applyFavicons(node)
1110        } else {
1111          node.querySelectorAll<HTMLElement>('.plugin-tabs--content').forEach(
1112            (panel) => {
1113              wrapTablesInRoot(panel)
1114              initCopyButtonsInRoot(panel)
1115              if (faviconsEnabled.value) applyFavicons(panel)
1116            }
1117          )
1118        }
1119      }
1120    }
1121  })
1122  copyButtonObserver.observe(document.body, { childList: true, subtree: true })
1123}
1124
1125watch(
1126  () => route.path,
1127  () => nextTick(() => { initTitleOnly(); setupManualCopyButtons() }),
1128  { flush: 'post' }
1129)
1130
1131onMounted(() => {
1132  if (import.meta.env.SSR) return
1133
1134  window.addEventListener(BOOKMARK_CHANGE_EVENT, syncTocBookmarkStates)
1135
1136  initTitleOnly()
1137  nextTick(setupManualCopyButtons)
1138
1139  // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
1140  const tooltipEl = document.createElement('div')
1141  tooltipEl.className = 'icon-tip-popup'
1142  document.body.appendChild(tooltipEl)
1143
1144  const showTooltip = (e: MouseEvent) => {
1145    const target = (e.target as HTMLElement).closest('.icon-tip') as
1146      | HTMLElement
1147      | null
1148    if (!target) return
1149    const tip = target.dataset.tip
1150    if (!tip) return
1151
1152    tooltipEl.textContent = tip
1153    tooltipEl.classList.add('visible')
1154
1155    const rect = target.getBoundingClientRect()
1156    const tipWidth = tooltipEl.offsetWidth
1157    const tipHeight = tooltipEl.offsetHeight
1158    let left = rect.left + rect.width / 2 - tipWidth / 2
1159    left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
1160    const top = rect.top - tipHeight - 6
1161
1162    tooltipEl.style.left = `${left}px`
1163    tooltipEl.style.top = `${top}px`
1164  }
1165
1166  const hideTooltip = () => {
1167    tooltipEl.classList.remove('visible')
1168  }
1169
1170  document.addEventListener('mouseover', showTooltip)
1171  document.addEventListener('mouseout', hideTooltip)
1172  document.addEventListener('scroll', hideTooltip, true)
1173
1174  const onCaptureClick = (e: MouseEvent) => {
1175    if (!e.isTrusted) return
1176    const link = (e.target as HTMLElement).closest<HTMLAnchorElement>('a[href]')
1177    if (!link) return
1178    const raw = link.getAttribute('href') ?? ''
1179
1180    // ── Tab link: #tab-name or already-rewritten /path?tabs=name ──────────
1181    const tabFromHash = raw.startsWith('#' + TAB_LINK_MARKER)
1182      ? raw.slice(1 + TAB_LINK_MARKER.length)
1183      : null
1184    let tabFromQuery: string | null = null
1185    if (
1186      !e.defaultPrevented &&
1187      !tabFromHash &&
1188      raw.includes(`?${TAB_QUERY_PARAM}=`) &&
1189      !raw.includes('#')
1190    ) {
1191      try {
1192        const url = new URL(raw, window.location.href)
1193        const samePage = url.origin === window.location.origin &&
1194          url.pathname === window.location.pathname
1195        tabFromQuery = samePage
1196          ? url.searchParams.get(TAB_QUERY_PARAM)
1197          : null
1198      } catch {
1199        tabFromQuery = null
1200      }
1201    }
1202    const tabName = tabFromHash ?? tabFromQuery
1203
1204    if (tabName) {
1205      e.preventDefault()
1206      e.stopImmediatePropagation()
1207      window.history.pushState(null, '', buildUrlWithTabs([tabName]))
1208      rewriteAnchorLinks()
1209      void (async () => {
1210        const tabs = await selectTabsByPath([tabName])
1211        if (tabs) scrollToElement(getSelectedTabScrollTarget(tabs), false)
1212      })()
1213      return
1214    }
1215
1216    // ── Plain heading link: #name or already-rewritten /path#name ─────────
1217    // Only intercept when ?tabs= is present — otherwise let the router handle normally.
1218    if (!new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)) {
1219      return
1220    }
1221
1222    let hash: string | null = null
1223    if (raw.startsWith('#') && raw.length > 1) {
1224      hash = raw.slice(1)
1225    } else if (raw.startsWith(window.location.pathname + '#')) {
1226      hash = raw.slice(window.location.pathname.length + 1)
1227    }
1228    if (!hash) return
1229
1230    e.preventDefault()
1231    e.stopImmediatePropagation()
1232    window.history.pushState(null, '', `${window.location.pathname}#${hash}`)
1233    rewriteAnchorLinks()
1234    void tryOpenAnchoredContent()
1235  }
1236
1237  document.addEventListener('click', onCaptureClick, { capture: true })
1238
1239  useEventListener(document, 'click', (e: MouseEvent) => {
1240    if (!e.isTrusted) return
1241    queueTabQueryUpdateForSelection(e.target)
1242    queueCollapsibleQueryUpdate(e.target)
1243  })
1244
1245  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
1246    if (!e.isTrusted || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) {
1247      return
1248    }
1249
1250    queueTabQueryUpdateForSelection(e.target)
1251  })
1252
1253  onUnmounted(() => {
1254    document.removeEventListener('click', onCaptureClick, { capture: true })
1255    document.removeEventListener('mouseover', showTooltip)
1256    document.removeEventListener('mouseout', hideTooltip)
1257    document.removeEventListener('scroll', hideTooltip, true)
1258    tooltipEl.remove()
1259  })
1260
1261  // Arrow key scrolling + Escape close for sidebars and content
1262  let activeScrollTarget: HTMLElement | Window = window
1263
1264  useEventListener(document, 'pointerdown', (e: PointerEvent) => {
1265    const el = e.target as HTMLElement
1266    if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
1267      activeScrollTarget = sidebarRef.value
1268    } else if (el.closest('.VPSidebar')) {
1269      activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
1270    } else {
1271      activeScrollTarget = window
1272    }
1273  })
1274
1275  const pxPerFrame = 18
1276  let scrollDirection = 0
1277  let scrollRaf = 0
1278
1279  function tickScroll() {
1280    if (!scrollDirection) return
1281    activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
1282    scrollRaf = requestAnimationFrame(tickScroll)
1283  }
1284
1285  function stopScroll() {
1286    scrollDirection = 0
1287    cancelAnimationFrame(scrollRaf)
1288  }
1289
1290  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
1291    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
1292      return
1293    }
1294
1295    if (e.key === 'Escape') {
1296      if (homeSidebarOpen.value) homeSidebarOpen.value = false
1297      return
1298    }
1299
1300    e.preventDefault()
1301    const dir = e.key === 'ArrowDown' ? 1 : -1
1302    if (scrollDirection === dir) return
1303    scrollDirection = dir
1304    cancelAnimationFrame(scrollRaf)
1305    scrollRaf = requestAnimationFrame(tickScroll)
1306  })
1307
1308  useEventListener(document, 'keyup', (e: KeyboardEvent) => {
1309    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
1310  })
1311
1312  onUnmounted(stopScroll)
1313
1314  // Close home NavScreen on outside click
1315  useEventListener(document, 'click', (e: Event) => {
1316    if (!isHome.value) return
1317    const screen = document.getElementById('VPNavScreen')
1318    if (!screen) return
1319    const hamburger = document.querySelector('.VPNavBarHamburger')
1320    if (
1321      screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
1322    ) return
1323    requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
1324  })
1325})
1326
1327onUnmounted(() => {
1328  outlineFollowObserver?.disconnect()
1329  copyButtonObserver?.disconnect()
1330  tocMutationObserver?.disconnect()
1331  faviconObserver?.disconnect()
1332  cancelAnimationFrame(outlineFollowRaf)
1333  cancelAnimationFrame(tocRaf)
1334  window.removeEventListener(BOOKMARK_CHANGE_EVENT, syncTocBookmarkStates)
1335})
1336</script>
1337
1338<template>
1339  <Layout>
1340    <template #layout-top>
1341      <!-- Home sidebar menu -->
1342      <template v-if="isHome">
1343        <Transition name="home-fade">
1344          <div
1345            v-if="homeSidebarOpen"
1346            class="home-sidebar-backdrop"
1347            @click="homeSidebarOpen = false"
1348          />
1349        </Transition>
1350        <Transition name="home-slide" @after-enter="onSidebarEnter">
1351          <aside
1352            v-if="homeSidebarOpen"
1353            ref="sidebarRef"
1354            class="home-sidebar"
1355            tabindex="-1"
1356            @click.stop
1357          >
1358            <div class="home-sidebar-header">
1359              <a href="/" class="home-sidebar-logo">
1360                <img
1361                  v-if="logoSrc"
1362                  :src="logoSrc"
1363                  class="home-sidebar-logo-img"
1364                  alt="Logo"
1365                />
1366                <span>{{ theme.siteTitle ?? site.title }}</span>
1367              </a>
1368            </div>
1369            <nav id="VPSidebarNav" class="home-sidebar-nav">
1370              <VPSidebarGroup :items="homeSidebarGroups" />
1371              <SidebarCard />
1372            </nav>
1373          </aside>
1374        </Transition>
1375      </template>
1376    </template>
1377    <template #doc-before>
1378      <!-- Breadcrumb Navigation -->
1379      <nav
1380        v-if="breadcrumbs.length > 0"
1381        class="breadcrumb mb-6 text-sm text-text-2"
1382        aria-label="Breadcrumb"
1383      >
1384        <ol class="flex flex-wrap items-center gap-2">
1385          <li>
1386            <a href="/" class="hover:text-primary transition-colors">
1387              <span class="i-lucide:home"></span>
1388            </a>
1389          </li>
1390          <li
1391            v-for="(crumb, index) in breadcrumbs"
1392            :key="crumb.link || index"
1393            class="flex items-center gap-2"
1394          >
1395            <span
1396              class="i-lucide:chevron-right text-text-3 flex-shrink-0"
1397            ></span>
1398            <span
1399              v-if="index === breadcrumbs.length - 1"
1400              v-html="crumb.text"
1401              class="font-medium text-text-1 break-words"
1402            ></span>
1403            <a
1404              v-else
1405              :href="crumb.link"
1406              v-html="crumb.text"
1407              class="hover:text-primary transition-colors break-words"
1408            ></a>
1409          </li>
1410        </ol>
1411      </nav>
1412    </template>
1413    <template #not-found>
1414      <NotFoundComponent />
1415    </template>
1416    <template #sidebar-nav-after>
1417      <SidebarCard />
1418    </template>
1419    <template #home-hero-info-before>
1420      <AnnouncementPill />
1421    </template>
1422    <template #nav-bar-content-after>
1423      <NavActions />
1424    </template>
1425    <template #nav-screen-content-before>
1426      <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
1427        <VPSidebarGroup :items="homeSidebarGroups" />
1428      </nav>
1429    </template>
1430    <template #nav-screen-content-after>
1431      <NolebaseEnhancedReadabilitiesScreenMenu />
1432    </template>
1433    <template #layout-bottom>
1434      <SiteFooter />
1435    </template>
1436
1437    <template #nav-bar-title-before>
1438      <span
1439        v-if="isHome"
1440        class="home-menu-btn"
1441        role="button"
1442        tabindex="0"
1443        aria-label="Menu"
1444        @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1445        @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
1446      >
1447        <span class="vpi-align-left home-menu-icon" />
1448      </span>
1449    </template>
1450  </Layout>
1451</template>