docs/.vitepress/theme/Layout.vue

c739d46770b526bab469834941ec98439942ca2c
wotaku/docs/.vitepress/theme/Layout.vue

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