docs/.vitepress/theme/Layout.vue

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

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