docs/.vitepress/theme/Layout.vue

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

921 lines · 26553 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 NotFoundComponent from './components/NotFound.vue'
 32import {
 33  NolebaseEnhancedReadabilitiesMenu,
 34  NolebaseEnhancedReadabilitiesScreenMenu
 35} from './components/settings'
 36import SidebarCard from './components/SidebarCard.vue'
 37import { LowEndDeviceModeStorageKey, TakodachiStorageKey } from './constants'
 38import { v2add, v2mag, v2norm, v2smul, v2sub, type Vec2D } from './math'
 39
 40const route = useRoute()
 41const { frontmatter, site, theme } = useData()
 42const { Layout } = DefaultTheme
 43
 44// Home sidebar menu
 45const isHome = computed(() => frontmatter.value.layout === 'home')
 46const homeSidebarOpen = ref(false)
 47const sidebarRef = ref<HTMLElement | null>(null)
 48const homeSidebarGroups = getSidebarGroups(sidebar as any)
 49const logoSrc = computed(() =>
 50  typeof theme.value.logo === 'string'
 51    ? theme.value.logo
 52    : theme.value.logo?.src
 53)
 54
 55watch(() => route.path, () => {
 56  homeSidebarOpen.value = false
 57})
 58
 59let searchNavigated = false
 60let searchQuery = ''
 61
 62if (!import.meta.env.SSR) {
 63  useEventListener(window, 'search-nav', (event) => {
 64    searchNavigated = true
 65    searchQuery = event instanceof CustomEvent &&
 66        typeof event.detail?.query === 'string'
 67      ? event.detail.query
 68      : ''
 69  })
 70}
 71
 72const nextFrame = () =>
 73  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
 74
 75const getSearchTerms = (query: string) =>
 76  query
 77    .toLowerCase()
 78    .split(/\s+/)
 79    .map((term) => term.trim())
 80    .filter(Boolean)
 81
 82const getTargetByHash = (hash: string) => {
 83  const ids = [hash]
 84  try {
 85    const decoded = decodeURIComponent(hash)
 86    if (decoded !== hash) ids.unshift(decoded)
 87  } catch {
 88    /* keep the raw hash */
 89  }
 90
 91  for (const id of ids) {
 92    const target = document.getElementById(id)
 93    if (target) return target
 94  }
 95}
 96
 97const getScrollTargetForAnchor = (target: HTMLElement) => {
 98  if (target.classList.contains('tab-search-heading')) {
 99    return target.closest<HTMLElement>('.plugin-tabs') ?? target
100  }
101
102  return target
103}
104
105const TAB_QUERY_PARAM = 'tabs'
106
107const getRequestedTabPath = () => {
108  const value = new URLSearchParams(window.location.search).get(
109    TAB_QUERY_PARAM
110  )
111  return value
112    ?.split(',')
113    .map((tab) => tab.trim())
114    .filter(Boolean) ?? []
115}
116
117const buildUrlWithTabs = (tabs: string[], hash = '') => {
118  const params = new URLSearchParams(window.location.search)
119  params.delete(TAB_QUERY_PARAM)
120
121  const queryParts = [
122    params.toString(),
123    tabs.length
124      ? `${TAB_QUERY_PARAM}=${
125        tabs.map((tab) => encodeURIComponent(tab)).join(',')
126      }`
127      : ''
128  ].filter(Boolean)
129
130  return `${window.location.pathname}${
131    queryParts.length ? `?${queryParts.join('&')}` : ''
132  }${hash ? `#${encodeURIComponent(hash)}` : ''}`
133}
134
135const getSelectedTabAnchor = (tabs: HTMLElement) =>
136  tabs.querySelector<HTMLButtonElement>(
137    '.plugin-tabs--tab[aria-selected="true"][data-tab-anchor]'
138  )?.dataset.tabAnchor
139
140const getPanelForTabButton = (button: HTMLButtonElement) => {
141  const panelId = button.getAttribute('aria-controls')
142  return panelId ? document.getElementById(panelId) : undefined
143}
144
145const getTabPathForGroup = (tabs: HTMLElement) => {
146  const groups: HTMLElement[] = []
147  let currentTabs: HTMLElement | null = tabs
148
149  while (currentTabs) {
150    groups.unshift(currentTabs)
151    const parentPanel = currentTabs.parentElement?.closest<HTMLElement>(
152      '.plugin-tabs--content[data-tab-anchor]'
153    )
154    currentTabs = parentPanel?.closest<HTMLElement>('.plugin-tabs') ?? null
155  }
156
157  return groups
158    .map((group) => getSelectedTabAnchor(group))
159    .filter((tab): tab is string => Boolean(tab))
160}
161
162const updateQueryForSelectedTab = async (tabs: HTMLElement) => {
163  await nextTick()
164  await nextFrame()
165
166  const tabPath = getTabPathForGroup(tabs)
167  if (!tabPath.length) return
168
169  const nextUrl = buildUrlWithTabs(tabPath)
170  const currentUrl =
171    `${window.location.pathname}${window.location.search}${window.location.hash}`
172  if (nextUrl === currentUrl) return
173
174  window.history.pushState(null, '', nextUrl)
175  rewriteAnchorLinks()
176}
177
178const queueTabQueryUpdateForSelection = (target: EventTarget | null) => {
179  if (!(target instanceof HTMLElement)) return
180
181  const button = target.closest<HTMLButtonElement>(
182    '.plugin-tabs--tab[role="tab"]'
183  )
184  const tabs = button?.closest<HTMLElement>('.plugin-tabs')
185  if (tabs) void updateQueryForSelectedTab(tabs)
186}
187
188const TAB_LINK_MARKER = 'tab-'
189
190const rewriteAnchorLinks = () => {
191  const origin = window.location.origin
192  const pathname = window.location.pathname
193
194  document
195    .querySelectorAll<HTMLAnchorElement>('.VPDoc a[href]')
196    .forEach((link) => {
197      // Accept either the original `#…` form or a previously-rewritten absolute URL.
198      const raw = link.getAttribute('href') ?? ''
199      let fragment: string | null = null
200      if (raw.startsWith('#') && raw.length > 1) {
201        fragment = raw.slice(1)
202      } else if (raw.startsWith(origin + pathname + '#')) {
203        fragment = raw.slice((origin + pathname + '#').length)
204      } else if (raw.startsWith(origin + pathname + '?')) {
205        // Already rewritten as a tab link — re-derive the tab name and re-stamp.
206        const qs = raw.slice((origin + pathname + '?').length).split('#')[0]
207        const tabName = new URLSearchParams(qs).get(TAB_QUERY_PARAM)
208        if (tabName) {
209          const href = `${origin}${pathname}?${TAB_QUERY_PARAM}=${encodeURIComponent(tabName)}`
210          if (link.getAttribute('href') !== href) link.setAttribute('href', href)
211        }
212        return
213      } else {
214        return
215      }
216
217      const isTabLink = fragment.startsWith(TAB_LINK_MARKER)
218      const name = (isTabLink
219        ? fragment.slice(TAB_LINK_MARKER.length)
220        : fragment).trim()
221      if (!name) return
222
223      // Use absolute URLs so the browser's Copy Link has nothing to merge with
224      // the current ?tabs= query.
225      const href = isTabLink
226        ? `${origin}${pathname}?${TAB_QUERY_PARAM}=${encodeURIComponent(name)}`
227        : `${origin}${pathname}#${name}`
228
229      if (link.getAttribute('href') !== href) link.setAttribute('href', href)
230    })
231}
232
233const selectTabsByPath = async (tabPath: string[]) => {
234  let root: ParentNode = document
235  let selectedTabs: HTMLElement | undefined
236
237  for (const anchor of tabPath) {
238    const button = root.querySelector<HTMLButtonElement>(
239      `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(anchor)}"]`
240    )
241    if (!button) return selectedTabs
242
243    const tabs = button.closest<HTMLElement>('.plugin-tabs')
244    if (!tabs) return selectedTabs
245
246    selectedTabs = tabs
247    if (button.getAttribute('aria-selected') !== 'true') {
248      button.click()
249      await nextTick()
250      await nextFrame()
251    }
252
253    root = getPanelForTabButton(button) ?? tabs
254  }
255
256  return selectedTabs
257}
258
259const selectLegacyTabHash = async (hash: string) => {
260  const button = document.querySelector<HTMLButtonElement>(
261    `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(hash)}"]`
262  )
263  if (!button) return
264
265  if (button.getAttribute('aria-selected') !== 'true') {
266    button.click()
267    await nextTick()
268    await nextFrame()
269  }
270
271  const tabs = button.closest<HTMLElement>('.plugin-tabs')
272  if (tabs) {
273    window.history.replaceState(null, '', buildUrlWithTabs([hash]))
274  }
275  return tabs
276}
277
278const getSelectedTabScrollTarget = (tabs: HTMLElement) => {
279  const selectedTab = tabs.querySelector<HTMLButtonElement>(
280    '.plugin-tabs--tab[aria-selected="true"]'
281  )
282  return selectedTab ? getPanelForTabButton(selectedTab) ?? tabs : tabs
283}
284
285const scrollToElement = (target: HTMLElement, smooth = true) => {
286  requestAnimationFrame(() => {
287    requestAnimationFrame(() => {
288      const navBar = document.querySelector<HTMLElement>('.VPNavBar')
289      const navOffset = navBar ? navBar.offsetHeight : 0
290      window.scrollTo({
291        top: target.getBoundingClientRect().top + window.scrollY - navOffset,
292        behavior: smooth &&
293            !window.matchMedia('(prefers-reduced-motion: reduce)').matches
294          ? 'smooth'
295          : 'auto'
296      })
297      target.setAttribute('tabindex', '-1')
298      target.focus({ preventScroll: true })
299    })
300  })
301}
302
303const openCollapsibles = async (target: HTMLElement) => {
304  const activeTarget = target
305  let scrollTarget = getScrollTargetForAnchor(activeTarget)
306  let el: HTMLElement | null = activeTarget
307
308  while ((el = el.closest('details'))) {
309    el.open = true
310    scrollTarget = el
311    el = el.parentElement
312  }
313
314  const tagName = activeTarget.tagName
315  if (tagName.length === 2 && tagName[0] === 'H') {
316    const level = +tagName[1]
317    if (level >= 1 && level <= 6) {
318      const terms = getSearchTerms(searchQuery)
319      const detailsContainsTerms = (d: HTMLElement) => {
320        if (!terms.length) return false
321        const text = (d.textContent ?? '').toLowerCase()
322        return terms.every((term) => text.includes(term))
323      }
324
325      let sibling = activeTarget.nextElementSibling
326
327      while (sibling) {
328        const siblingTag = sibling.tagName
329        if (
330          siblingTag.length === 2 && siblingTag[0] === 'H' &&
331          +siblingTag[1] <= level
332        ) break
333
334        if (siblingTag === 'DETAILS') {
335          if (detailsContainsTerms(sibling as HTMLElement)) {
336            ;(sibling as HTMLDetailsElement).open = true
337            if (scrollTarget === activeTarget) {
338              scrollTarget = sibling as HTMLElement
339            }
340          }
341        }
342
343        const nested = sibling.getElementsByTagName('details')
344        for (let i = 0, len = nested.length; i < len; i++) {
345          if (detailsContainsTerms(nested[i])) {
346            nested[i].open = true
347            if (scrollTarget === activeTarget) scrollTarget = nested[i]
348          }
349        }
350
351        sibling = sibling.nextElementSibling
352      }
353    }
354  }
355
356  await nextTick()
357  await nextFrame()
358
359  scrollToElement(scrollTarget)
360}
361
362const resetSearchNavigation = () => {
363  searchNavigated = false
364  searchQuery = ''
365}
366
367const tryOpenAnchoredContent = async () => {
368  await nextTick()
369  await nextFrame()
370
371  const requestedTabs = getRequestedTabPath()
372  const selectedTabs = requestedTabs.length
373    ? await selectTabsByPath(requestedTabs)
374    : undefined
375  const hash = window.location.hash.slice(1)
376
377  if (!hash) {
378    resetSearchNavigation()
379    if (selectedTabs) {
380      scrollToElement(getSelectedTabScrollTarget(selectedTabs), false)
381    }
382    return
383  }
384
385  let target = getTargetByHash(hash)
386
387  if (!target && !requestedTabs.length) {
388    const legacyTabs = await selectLegacyTabHash(hash)
389    if (legacyTabs) {
390      resetSearchNavigation()
391      scrollToElement(getSelectedTabScrollTarget(legacyTabs), false)
392      return
393    }
394  }
395
396  if (!target) {
397    if (searchNavigated) resetSearchNavigation()
398    return
399  }
400
401  if (searchNavigated) {
402    await openCollapsibles(target)
403    resetSearchNavigation()
404    return
405  }
406
407  const isTabRelatedTarget =
408    target.classList.contains('tab-search-heading') ||
409    Boolean(target.closest('.plugin-tabs'))
410
411  if (
412    !isTabRelatedTarget &&
413    new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)
414  ) {
415    window.history.replaceState(null, '', buildUrlWithTabs([], hash))
416    scrollToElement(getScrollTargetForAnchor(target), false)
417    return
418  }
419
420  if (
421    !requestedTabs.length && target.classList.contains('tab-search-heading')
422  ) {
423    const tabs = target.closest<HTMLElement>('.plugin-tabs')
424    if (tabs) {
425      window.history.replaceState(
426        null,
427        '',
428        buildUrlWithTabs(getTabPathForGroup(tabs))
429      )
430    }
431  }
432
433  if (
434    selectedTabs ||
435    target.classList.contains('tab-search-heading')
436  ) {
437    scrollToElement(getScrollTargetForAnchor(target), false)
438  }
439}
440
441const rewriteAnchorLinksDeferred = () =>
442  nextTick(() => rewriteAnchorLinks())
443
444onMounted(tryOpenAnchoredContent)
445onMounted(rewriteAnchorLinksDeferred)
446watch(() => route.data, () => {
447  void tryOpenAnchoredContent()
448  rewriteAnchorLinksDeferred()
449}, { flush: 'post' })
450watch(() => route.query, () => {
451  void tryOpenAnchoredContent()
452  rewriteAnchorLinksDeferred()
453}, { flush: 'post' })
454watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
455
456function onSidebarEnter() {
457  sidebarRef.value?.focus()
458}
459
460interface BreadcrumbItem {
461  text: string
462  link?: string
463}
464
465const buildBreadcrumbs = (
466  items: Theme.SidebarItem[],
467  currentPath: string
468): BreadcrumbItem[] => {
469  for (const item of items) {
470    // Check if this item matches the current path
471    if (item.link === currentPath) {
472      return [
473        {
474          text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
475          link: item.link
476        }
477      ]
478    }
479
480    // Check nested items
481    if (item.items) {
482      const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
483      if (nestedBreadcrumbs.length > 0) {
484        return [
485          {
486            text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
487            link: item.link
488          },
489          ...nestedBreadcrumbs
490        ]
491      }
492    }
493  }
494  return []
495}
496
497const breadcrumbs = computed(() => {
498  const currentPath = route.path
499  // @ts-expect-error
500  return buildBreadcrumbs(sidebar, currentPath)
501})
502
503// Respect user's reduced motion preferences
504const prefs = usePreferredReducedMotion()
505const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
506const reduceBlurEffects = computed(() => lowEndDeviceMode.value === 'on')
507
508watchEffect(() => {
509  if (import.meta.env.SSR) return
510
511  document.documentElement.classList.toggle(
512    'reduce-blur-effects',
513    reduceBlurEffects.value
514  )
515})
516
517const speed = 2
518const snapThreshold = 5 // px
519
520const takodachiRef = ref<HTMLImageElement | null>(null)
521let mousePos: Vec2D | null = null
522let target: Vec2D | null = null
523let offset: Vec2D = [0, 0]
524
525const position = ref({
526  x: 0,
527  y: 0
528})
529
530const updateMousePos = (e: MouseEvent | TouchEvent) => {
531  if (e instanceof MouseEvent) {
532    mousePos = [e.clientX, e.clientY]
533  } else {
534    mousePos = [e.touches[0].clientX, e.touches[0].clientY]
535  }
536}
537
538const takodachiDisable = ref<(() => void) | null>(null)
539const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
540
541const reloadTakodachi = () => {
542  takodachiDisable.value?.()
543
544  if (prefs.value === 'reduce') return
545  const saved = takodachiToggledOn
546  if (saved.value === false) return
547
548  window.addEventListener('mousemove', updateMousePos)
549  window.addEventListener('touchstart', updateMousePos)
550
551  const chaser = takodachiRef!.value
552  if (chaser) {
553    offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
554    setTimeout(() => {
555      chaser.classList.remove('opacity-0')
556    }, 1000)
557  }
558
559  const intervalId = setInterval(() => {
560    if (!mousePos) return
561
562    const currentPos: Vec2D = [
563      position.value.x + offset[0],
564      position.value.y + offset[1]
565    ]
566
567    target = target ?? currentPos
568
569    const diff = v2sub(mousePos, currentPos)
570
571    target = v2mag(diff) < snapThreshold
572      ? mousePos
573      : v2add(target, v2smul(v2norm(diff), speed))
574
575    const finalVec = v2sub(target, offset)
576
577    position.value = { x: finalVec[0], y: finalVec[1] }
578  }, 10)
579
580  takodachiDisable.value = () => {
581    chaser?.classList.add('opacity-0')
582
583    window.removeEventListener('mousemove', updateMousePos)
584    window.removeEventListener('touchstart', updateMousePos)
585    clearInterval(intervalId)
586
587    takodachiDisable.value = null
588  }
589}
590
591function initTitleOnly() {
592  document.querySelectorAll('.custom-block').forEach(block => {
593    const children = [...block.children]
594    const hasOnlyTitle = children.every(el =>
595      el.classList.contains('custom-block-title')
596    )
597    if (hasOnlyTitle) block.classList.add('title-only')
598  })
599}
600
601watch(
602  () => route.path,
603  () => nextTick(() => initTitleOnly()),
604  { flush: 'post' }
605)
606
607onMounted(() => {
608  if (import.meta.env.SSR) return
609
610  initTitleOnly()
611
612  // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
613  const tooltipEl = document.createElement('div')
614  tooltipEl.className = 'icon-tip-popup'
615  document.body.appendChild(tooltipEl)
616
617  const showTooltip = (e: MouseEvent) => {
618    const target = (e.target as HTMLElement).closest('.icon-tip') as
619      | HTMLElement
620      | null
621    if (!target) return
622    const tip = target.dataset.tip
623    if (!tip) return
624
625    tooltipEl.textContent = tip
626    tooltipEl.classList.add('visible')
627
628    const rect = target.getBoundingClientRect()
629    const tipWidth = tooltipEl.offsetWidth
630    const tipHeight = tooltipEl.offsetHeight
631    let left = rect.left + rect.width / 2 - tipWidth / 2
632    left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
633    const top = rect.top - tipHeight - 6
634
635    tooltipEl.style.left = `${left}px`
636    tooltipEl.style.top = `${top}px`
637  }
638
639  const hideTooltip = () => {
640    tooltipEl.classList.remove('visible')
641  }
642
643  document.addEventListener('mouseover', showTooltip)
644  document.addEventListener('mouseout', hideTooltip)
645  document.addEventListener('scroll', hideTooltip, true)
646
647  const onCaptureClick = (e: MouseEvent) => {
648    if (!e.isTrusted) return
649    const link = (e.target as HTMLElement).closest<HTMLAnchorElement>('a[href]')
650    if (!link) return
651    const raw = link.getAttribute('href') ?? ''
652
653    // ── Tab link: #tab-name or already-rewritten /path?tabs=name ──────────
654    const tabFromHash = raw.startsWith('#' + TAB_LINK_MARKER)
655      ? raw.slice(1 + TAB_LINK_MARKER.length)
656      : null
657    const tabFromQuery =
658      !tabFromHash && raw.includes(`?${TAB_QUERY_PARAM}=`) && !raw.includes('#')
659        ? new URLSearchParams(raw.split('?')[1]).get(TAB_QUERY_PARAM)
660        : null
661    const tabName = tabFromHash ?? tabFromQuery
662
663    if (tabName) {
664      e.preventDefault()
665      e.stopImmediatePropagation()
666      window.history.pushState(null, '', buildUrlWithTabs([tabName]))
667      rewriteAnchorLinks()
668      void (async () => {
669        const tabs = await selectTabsByPath([tabName])
670        if (tabs) scrollToElement(getSelectedTabScrollTarget(tabs), false)
671      })()
672      return
673    }
674
675    // ── Plain heading link: #name or already-rewritten /path#name ─────────
676    // Only intercept when ?tabs= is present — otherwise let the router handle normally.
677    if (!new URLSearchParams(window.location.search).has(TAB_QUERY_PARAM)) return
678
679    let hash: string | null = null
680    if (raw.startsWith('#') && raw.length > 1) {
681      hash = raw.slice(1)
682    } else if (raw.startsWith(window.location.pathname + '#')) {
683      hash = raw.slice(window.location.pathname.length + 1)
684    }
685    if (!hash) return
686
687    e.preventDefault()
688    e.stopImmediatePropagation()
689    window.history.pushState(null, '', `${window.location.pathname}#${hash}`)
690    rewriteAnchorLinks()
691    void tryOpenAnchoredContent()
692  }
693
694  document.addEventListener('click', onCaptureClick, { capture: true })
695
696  useEventListener(document, 'click', (e: MouseEvent) => {
697    if (!e.isTrusted) return
698    queueTabQueryUpdateForSelection(e.target)
699  })
700
701  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
702    if (!e.isTrusted || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) {
703      return
704    }
705
706    queueTabQueryUpdateForSelection(e.target)
707  })
708
709  onUnmounted(() => {
710    document.removeEventListener('click', onCaptureClick, { capture: true })
711    document.removeEventListener('mouseover', showTooltip)
712    document.removeEventListener('mouseout', hideTooltip)
713    document.removeEventListener('scroll', hideTooltip, true)
714    tooltipEl.remove()
715  })
716
717  // Arrow key scrolling + Escape close for sidebars and content
718  let activeScrollTarget: HTMLElement | Window = window
719
720  useEventListener(document, 'pointerdown', (e: PointerEvent) => {
721    const el = e.target as HTMLElement
722    if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
723      activeScrollTarget = sidebarRef.value
724    } else if (el.closest('.VPSidebar')) {
725      activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
726    } else {
727      activeScrollTarget = window
728    }
729  })
730
731  const pxPerFrame = 18
732  let scrollDirection = 0
733  let scrollRaf = 0
734
735  function tickScroll() {
736    if (!scrollDirection) return
737    activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
738    scrollRaf = requestAnimationFrame(tickScroll)
739  }
740
741  function stopScroll() {
742    scrollDirection = 0
743    cancelAnimationFrame(scrollRaf)
744  }
745
746  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
747    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
748      return
749    }
750
751    if (e.key === 'Escape') {
752      if (homeSidebarOpen.value) homeSidebarOpen.value = false
753      return
754    }
755
756    e.preventDefault()
757    const dir = e.key === 'ArrowDown' ? 1 : -1
758    if (scrollDirection === dir) return
759    scrollDirection = dir
760    cancelAnimationFrame(scrollRaf)
761    scrollRaf = requestAnimationFrame(tickScroll)
762  })
763
764  useEventListener(document, 'keyup', (e: KeyboardEvent) => {
765    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
766  })
767
768  onUnmounted(stopScroll)
769
770  // Close home NavScreen on outside click
771  useEventListener(document, 'click', (e: Event) => {
772    if (!isHome.value) return
773    const screen = document.getElementById('VPNavScreen')
774    if (!screen) return
775    const hamburger = document.querySelector('.VPNavBarHamburger')
776    if (
777      screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
778    ) return
779    requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
780  })
781
782  // Storage changed in other documents.
783  useEventListener(window, 'storage', () => {
784    reloadTakodachi()
785  })
786
787  // Storage changed in the same document.
788  useEventListener(window, customStorageEventName, () => {
789    reloadTakodachi()
790  })
791
792  reloadTakodachi()
793})
794
795onUnmounted(() => {
796  takodachiDisable.value && takodachiDisable.value()
797})
798</script>
799
800<template>
801  <Layout>
802    <template #layout-top>
803      <img
804        id="takodachi"
805        ref="takodachiRef"
806        src="/takodachi.webp"
807        alt="Takodachi"
808        class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
809        :style="{
810          left: `${position.x}px`,
811          top: `${position.y}px`
812        }"
813      />
814      <!-- Home sidebar menu -->
815      <template v-if="isHome">
816        <Transition name="home-fade">
817          <div
818            v-if="homeSidebarOpen"
819            class="home-sidebar-backdrop"
820            @click="homeSidebarOpen = false"
821          />
822        </Transition>
823        <Transition name="home-slide" @after-enter="onSidebarEnter">
824          <aside
825            v-if="homeSidebarOpen"
826            ref="sidebarRef"
827            class="home-sidebar"
828            tabindex="-1"
829            @click.stop
830          >
831            <div class="home-sidebar-header">
832              <a href="/" class="home-sidebar-logo">
833                <img
834                  v-if="logoSrc"
835                  :src="logoSrc"
836                  class="home-sidebar-logo-img"
837                  alt="Logo"
838                />
839                <span>{{ theme.siteTitle ?? site.title }}</span>
840              </a>
841            </div>
842            <nav id="VPSidebarNav" class="home-sidebar-nav">
843              <VPSidebarGroup :items="homeSidebarGroups" />
844              <SidebarCard />
845            </nav>
846          </aside>
847        </Transition>
848      </template>
849    </template>
850    <template #doc-before>
851      <!-- Breadcrumb Navigation -->
852      <nav
853        v-if="breadcrumbs.length > 0"
854        class="breadcrumb mb-6 text-sm text-text-2"
855        aria-label="Breadcrumb"
856      >
857        <ol class="flex flex-wrap items-center gap-2">
858          <li>
859            <a href="/" class="hover:text-primary transition-colors">
860              <span class="i-lucide:home"></span>
861            </a>
862          </li>
863          <li
864            v-for="(crumb, index) in breadcrumbs"
865            :key="crumb.link || index"
866            class="flex items-center gap-2"
867          >
868            <span
869              class="i-lucide:chevron-right text-text-3 flex-shrink-0"
870            ></span>
871            <span
872              v-if="index === breadcrumbs.length - 1"
873              v-html="crumb.text"
874              class="font-medium text-text-1 break-words"
875            ></span>
876            <a
877              v-else
878              :href="crumb.link"
879              v-html="crumb.text"
880              class="hover:text-primary transition-colors break-words"
881            ></a>
882          </li>
883        </ol>
884      </nav>
885    </template>
886    <template #not-found>
887      <NotFoundComponent />
888    </template>
889    <template #sidebar-nav-after>
890      <SidebarCard />
891    </template>
892    <template #home-hero-info-before>
893      <AnnouncementPill />
894    </template>
895    <template #nav-bar-content-after>
896      <NolebaseEnhancedReadabilitiesMenu />
897    </template>
898    <template #nav-screen-content-before>
899      <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
900        <VPSidebarGroup :items="homeSidebarGroups" />
901      </nav>
902    </template>
903    <template #nav-screen-content-after>
904      <NolebaseEnhancedReadabilitiesScreenMenu />
905    </template>
906
907    <template #nav-bar-title-before>
908      <span
909        v-if="isHome"
910        class="home-menu-btn"
911        role="button"
912        tabindex="0"
913        aria-label="Menu"
914        @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
915        @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
916      >
917        <span class="vpi-align-left home-menu-icon" />
918      </span>
919    </template>
920  </Layout>
921</template>