docs/.vitepress/theme/Layout.vue

7b774cae81351666b54bdca55c379582beb10043
wotaku/docs/.vitepress/theme/Layout.vue

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form