docs/.vitepress/theme/Layout.vue

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

1322 lines · 39169 bytes

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