docs/.vitepress/theme/Layout.vue

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

640 lines · 18153 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    tryOpenCollapsibles()
 70  })
 71}
 72
 73const nextFrame = () =>
 74  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
 75
 76const getSearchTerms = (query: string) =>
 77  query
 78    .toLowerCase()
 79    .split(/\s+/)
 80    .map((term) => term.trim())
 81    .filter(Boolean)
 82
 83const getTabsInSearchScope = (target: HTMLElement) => {
 84  const tabs = new Set<HTMLElement>()
 85  const closestTabs = target.closest<HTMLElement>('.plugin-tabs')
 86  if (closestTabs) tabs.add(closestTabs)
 87
 88  const tagName = target.tagName
 89  if (tagName.length === 2 && tagName[0] === 'H') {
 90    const level = +tagName[1]
 91    if (level >= 1 && level <= 6) {
 92      let sibling = target.nextElementSibling
 93
 94      while (sibling) {
 95        const siblingTag = sibling.tagName
 96        if (
 97          siblingTag.length === 2 && siblingTag[0] === 'H' &&
 98          +siblingTag[1] <= level
 99        ) break
100
101        if (sibling.matches('.plugin-tabs')) tabs.add(sibling as HTMLElement)
102        sibling.querySelectorAll<HTMLElement>('.plugin-tabs').forEach((tab) => {
103          tabs.add(tab)
104        })
105
106        sibling = sibling.nextElementSibling
107      }
108    }
109  }
110
111  return [...tabs]
112}
113
114const selectTabContainingQuery = async (target: HTMLElement, query: string) => {
115  const terms = getSearchTerms(query)
116  if (!terms.length) return
117
118  for (const tabs of getTabsInSearchScope(target)) {
119    const selectedTab = tabs.querySelector<HTMLButtonElement>(
120      '.plugin-tabs--tab[aria-selected="true"]'
121    )
122    const buttons = tabs.querySelectorAll<HTMLButtonElement>(
123      '.plugin-tabs--tab[role="tab"]'
124    )
125
126    for (let i = 0, len = buttons.length; i < len; i++) {
127      const button = buttons[i]
128      button.click()
129      await nextTick()
130      await nextFrame()
131
132      const panelId = button.getAttribute('aria-controls')
133      const panel = panelId
134        ? document.getElementById(panelId)
135        : tabs.querySelector<HTMLElement>('.plugin-tabs--content')
136      const text = panel?.textContent?.toLowerCase() ?? ''
137
138      if (terms.every((term) => text.includes(term))) return
139    }
140
141    selectedTab?.click()
142    await nextTick()
143  }
144}
145
146const openCollapsibles = async (target: HTMLElement) => {
147  let scrollTarget = target
148  let el: HTMLElement | null = target
149
150  while ((el = el.closest('details'))) {
151    el.open = true
152    scrollTarget = el
153    el = el.parentElement
154  }
155
156  const tagName = target.tagName
157  if (tagName.length === 2 && tagName[0] === 'H') {
158    const level = +tagName[1]
159    if (level >= 1 && level <= 6) {
160      const terms = getSearchTerms(searchQuery)
161      const detailsContainsTerms = (d: HTMLElement) => {
162        if (!terms.length) return false
163        const text = (d.textContent ?? '').toLowerCase()
164        return terms.every((term) => text.includes(term))
165      }
166
167      let sibling = target.nextElementSibling
168
169      while (sibling) {
170        const siblingTag = sibling.tagName
171        if (
172          siblingTag.length === 2 && siblingTag[0] === 'H' &&
173          +siblingTag[1] <= level
174        ) break
175
176        if (siblingTag === 'DETAILS') {
177          if (detailsContainsTerms(sibling as HTMLElement)) {
178            ;(sibling as HTMLDetailsElement).open = true
179            if (scrollTarget === target) scrollTarget = sibling as HTMLElement
180          }
181        }
182
183        const nested = sibling.getElementsByTagName('details')
184        for (let i = 0, len = nested.length; i < len; i++) {
185          if (detailsContainsTerms(nested[i])) {
186            nested[i].open = true
187            if (scrollTarget === target) scrollTarget = nested[i]
188          }
189        }
190
191        sibling = sibling.nextElementSibling
192      }
193    }
194  }
195
196  await selectTabContainingQuery(target, searchQuery)
197
198  requestAnimationFrame(() => {
199    requestAnimationFrame(() => {
200      const navBar = document.querySelector<HTMLElement>('.VPNavBar')
201      const navOffset = navBar ? navBar.offsetHeight : 0
202      window.scrollTo({
203        top: scrollTarget.getBoundingClientRect().top + window.scrollY -
204          navOffset,
205        behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches
206          ? 'auto'
207          : 'smooth'
208      })
209      scrollTarget.setAttribute('tabindex', '-1')
210      scrollTarget.focus({ preventScroll: true })
211    })
212  })
213}
214
215const tryOpenCollapsibles = async () => {
216  if (!searchNavigated) return
217  await nextTick()
218
219  requestAnimationFrame(() => {
220    const hash = window.location.hash.slice(1)
221    if (!hash) {
222      searchNavigated = false
223      return
224    }
225
226    const id = decodeURIComponent(hash)
227    const target = document.getElementById(id) || document.getElementById(hash)
228
229    if (target) {
230      openCollapsibles(target)
231      searchNavigated = false
232      searchQuery = ''
233    }
234  })
235}
236
237watch(() => route.data, tryOpenCollapsibles, { flush: 'post' })
238watch(() => route.hash, tryOpenCollapsibles, { flush: 'post' })
239
240function onSidebarEnter() {
241  sidebarRef.value?.focus()
242}
243
244interface BreadcrumbItem {
245  text: string
246  link?: string
247}
248
249const buildBreadcrumbs = (
250  items: Theme.SidebarItem[],
251  currentPath: string
252): BreadcrumbItem[] => {
253  for (const item of items) {
254    // Check if this item matches the current path
255    if (item.link === currentPath) {
256      return [
257        {
258          text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
259          link: item.link
260        }
261      ]
262    }
263
264    // Check nested items
265    if (item.items) {
266      const nestedBreadcrumbs = buildBreadcrumbs(item.items, currentPath)
267      if (nestedBreadcrumbs.length > 0) {
268        return [
269          {
270            text: item.text!.replace('mr-2 block w-4 h-4 bg-cover', '').trim(),
271            link: item.link
272          },
273          ...nestedBreadcrumbs
274        ]
275      }
276    }
277  }
278  return []
279}
280
281const breadcrumbs = computed(() => {
282  const currentPath = route.path
283  // @ts-expect-error
284  return buildBreadcrumbs(sidebar, currentPath)
285})
286
287// Respect user's reduced motion preferences
288const prefs = usePreferredReducedMotion()
289const lowEndDeviceMode = useStorage(LowEndDeviceModeStorageKey, 'off')
290const reduceBlurEffects = computed(() => lowEndDeviceMode.value === 'on')
291
292watchEffect(() => {
293  if (import.meta.env.SSR) return
294
295  document.documentElement.classList.toggle(
296    'reduce-blur-effects',
297    reduceBlurEffects.value
298  )
299})
300
301const speed = 2
302const snapThreshold = 5 // px
303
304const takodachiRef = ref<HTMLImageElement | null>(null)
305let mousePos: Vec2D | null = null
306let target: Vec2D | null = null
307let offset: Vec2D = [0, 0]
308
309const position = ref({
310  x: 0,
311  y: 0
312})
313
314const updateMousePos = (e: MouseEvent | TouchEvent) => {
315  if (e instanceof MouseEvent) {
316    mousePos = [e.clientX, e.clientY]
317  } else {
318    mousePos = [e.touches[0].clientX, e.touches[0].clientY]
319  }
320}
321
322const takodachiDisable = ref<(() => void) | null>(null)
323const takodachiToggledOn = useStorage(TakodachiStorageKey, false)
324
325const reloadTakodachi = () => {
326  takodachiDisable.value?.()
327
328  if (prefs.value === 'reduce') return
329  const saved = takodachiToggledOn
330  if (saved.value === false) return
331
332  window.addEventListener('mousemove', updateMousePos)
333  window.addEventListener('touchstart', updateMousePos)
334
335  const chaser = takodachiRef!.value
336  if (chaser) {
337    offset = v2smul([chaser.clientWidth, chaser.clientHeight], 0.5)
338    setTimeout(() => {
339      chaser.classList.remove('opacity-0')
340    }, 1000)
341  }
342
343  const intervalId = setInterval(() => {
344    if (!mousePos) return
345
346    const currentPos: Vec2D = [
347      position.value.x + offset[0],
348      position.value.y + offset[1]
349    ]
350
351    target = target ?? currentPos
352
353    const diff = v2sub(mousePos, currentPos)
354
355    target = v2mag(diff) < snapThreshold
356      ? mousePos
357      : v2add(target, v2smul(v2norm(diff), speed))
358
359    const finalVec = v2sub(target, offset)
360
361    position.value = { x: finalVec[0], y: finalVec[1] }
362  }, 10)
363
364  takodachiDisable.value = () => {
365    chaser?.classList.add('opacity-0')
366
367    window.removeEventListener('mousemove', updateMousePos)
368    window.removeEventListener('touchstart', updateMousePos)
369    clearInterval(intervalId)
370
371    takodachiDisable.value = null
372  }
373}
374
375function initTitleOnly() {
376  document.querySelectorAll('.custom-block').forEach(block => {
377    const children = [...block.children]
378    const hasOnlyTitle = children.every(el => el.classList.contains('custom-block-title'))
379    if (hasOnlyTitle) block.classList.add('title-only')
380  })
381}
382
383watch(
384  () => route.path,
385  () => nextTick(() => initTitleOnly()),
386  { flush: 'post' }
387)
388
389onMounted(() => {
390  if (import.meta.env.SSR) return
391
392  initTitleOnly()
393
394  // Icon tooltip: fixed-position popup appended to <body> to escape table overflow clipping
395  const tooltipEl = document.createElement('div')
396  tooltipEl.className = 'icon-tip-popup'
397  document.body.appendChild(tooltipEl)
398
399  const showTooltip = (e: MouseEvent) => {
400    const target = (e.target as HTMLElement).closest('.icon-tip') as
401      | HTMLElement
402      | null
403    if (!target) return
404    const tip = target.dataset.tip
405    if (!tip) return
406
407    tooltipEl.textContent = tip
408    tooltipEl.classList.add('visible')
409
410    const rect = target.getBoundingClientRect()
411    const tipWidth = tooltipEl.offsetWidth
412    const tipHeight = tooltipEl.offsetHeight
413    let left = rect.left + rect.width / 2 - tipWidth / 2
414    left = Math.max(8, Math.min(left, window.innerWidth - tipWidth - 8))
415    const top = rect.top - tipHeight - 6
416
417    tooltipEl.style.left = `${left}px`
418    tooltipEl.style.top = `${top}px`
419  }
420
421  const hideTooltip = () => {
422    tooltipEl.classList.remove('visible')
423  }
424
425  document.addEventListener('mouseover', showTooltip)
426  document.addEventListener('mouseout', hideTooltip)
427  document.addEventListener('scroll', hideTooltip, true)
428
429  onUnmounted(() => {
430    document.removeEventListener('mouseover', showTooltip)
431    document.removeEventListener('mouseout', hideTooltip)
432    document.removeEventListener('scroll', hideTooltip, true)
433    tooltipEl.remove()
434  })
435
436  // Arrow key scrolling + Escape close for sidebars and content
437  let activeScrollTarget: HTMLElement | Window = window
438
439  useEventListener(document, 'pointerdown', (e: PointerEvent) => {
440    const el = e.target as HTMLElement
441    if (homeSidebarOpen.value && sidebarRef.value?.contains(el)) {
442      activeScrollTarget = sidebarRef.value
443    } else if (el.closest('.VPSidebar')) {
444      activeScrollTarget = el.closest('.VPSidebar') as HTMLElement
445    } else {
446      activeScrollTarget = window
447    }
448  })
449
450  const pxPerFrame = 18
451  let scrollDirection = 0
452  let scrollRaf = 0
453
454  function tickScroll() {
455    if (!scrollDirection) return
456    activeScrollTarget.scrollBy({ top: scrollDirection * pxPerFrame })
457    scrollRaf = requestAnimationFrame(tickScroll)
458  }
459
460  function stopScroll() {
461    scrollDirection = 0
462    cancelAnimationFrame(scrollRaf)
463  }
464
465  useEventListener(document, 'keydown', (e: KeyboardEvent) => {
466    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Escape') {
467      return
468    }
469
470    if (e.key === 'Escape') {
471      if (homeSidebarOpen.value) homeSidebarOpen.value = false
472      return
473    }
474
475    e.preventDefault()
476    const dir = e.key === 'ArrowDown' ? 1 : -1
477    if (scrollDirection === dir) return
478    scrollDirection = dir
479    cancelAnimationFrame(scrollRaf)
480    scrollRaf = requestAnimationFrame(tickScroll)
481  })
482
483  useEventListener(document, 'keyup', (e: KeyboardEvent) => {
484    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') stopScroll()
485  })
486
487  onUnmounted(stopScroll)
488
489  // Close home NavScreen on outside click
490  useEventListener(document, 'click', (e: Event) => {
491    if (!isHome.value) return
492    const screen = document.getElementById('VPNavScreen')
493    if (!screen) return
494    const hamburger = document.querySelector('.VPNavBarHamburger')
495    if (
496      screen.contains(e.target as Node) || hamburger?.contains(e.target as Node)
497    ) return
498    requestAnimationFrame(() => (hamburger as HTMLElement)?.click())
499  })
500
501  // Storage changed in other documents.
502  useEventListener(window, 'storage', () => {
503    reloadTakodachi()
504  })
505
506  // Storage changed in the same document.
507  useEventListener(window, customStorageEventName, () => {
508    reloadTakodachi()
509  })
510
511  reloadTakodachi()
512})
513
514onUnmounted(() => {
515  takodachiDisable.value && takodachiDisable.value()
516})
517</script>
518
519<template>
520  <Layout>
521    <template #layout-top>
522      <img
523        id="takodachi"
524        ref="takodachiRef"
525        src="/takodachi.webp"
526        alt="Takodachi"
527        class="pointer-events-none fixed absolute z-[9999] h-10 w-10 opacity-0 transition-opacity duration-500"
528        :style="{
529          left: `${position.x}px`,
530          top: `${position.y}px`
531        }"
532      />
533      <!-- Home sidebar menu -->
534      <template v-if="isHome">
535        <Transition name="home-fade">
536          <div
537            v-if="homeSidebarOpen"
538            class="home-sidebar-backdrop"
539            @click="homeSidebarOpen = false"
540          />
541        </Transition>
542        <Transition name="home-slide" @after-enter="onSidebarEnter">
543          <aside
544            v-if="homeSidebarOpen"
545            ref="sidebarRef"
546            class="home-sidebar"
547            tabindex="-1"
548            @click.stop
549          >
550            <div class="home-sidebar-header">
551              <a href="/" class="home-sidebar-logo">
552                <img
553                  v-if="logoSrc"
554                  :src="logoSrc"
555                  class="home-sidebar-logo-img"
556                  alt="Logo"
557                />
558                <span>{{ theme.siteTitle ?? site.title }}</span>
559              </a>
560            </div>
561            <nav id="VPSidebarNav" class="home-sidebar-nav">
562              <VPSidebarGroup :items="homeSidebarGroups" />
563              <SidebarCard />
564            </nav>
565          </aside>
566        </Transition>
567      </template>
568    </template>
569    <template #doc-before>
570      <!-- Breadcrumb Navigation -->
571      <nav
572        v-if="breadcrumbs.length > 0"
573        class="breadcrumb mb-6 text-sm text-text-2"
574        aria-label="Breadcrumb"
575      >
576        <ol class="flex flex-wrap items-center gap-2">
577          <li>
578            <a href="/" class="hover:text-primary transition-colors">
579              <span class="i-lucide:home"></span>
580            </a>
581          </li>
582          <li
583            v-for="(crumb, index) in breadcrumbs"
584            :key="crumb.link || index"
585            class="flex items-center gap-2"
586          >
587            <span
588              class="i-lucide:chevron-right text-text-3 flex-shrink-0"
589            ></span>
590            <span
591              v-if="index === breadcrumbs.length - 1"
592              v-html="crumb.text"
593              class="font-medium text-text-1 break-words"
594            ></span>
595            <a
596              v-else
597              :href="crumb.link"
598              v-html="crumb.text"
599              class="hover:text-primary transition-colors break-words"
600            ></a>
601          </li>
602        </ol>
603      </nav>
604    </template>
605    <template #not-found>
606      <NotFoundComponent />
607    </template>
608    <template #sidebar-nav-after>
609      <SidebarCard />
610    </template>
611    <template #home-hero-info-before>
612      <AnnouncementPill />
613    </template>
614    <template #nav-bar-content-after>
615      <NolebaseEnhancedReadabilitiesMenu />
616    </template>
617    <template #nav-screen-content-before>
618      <nav v-if="isHome" id="VPSidebarNavMobile" class="home-screen-nav">
619        <VPSidebarGroup :items="homeSidebarGroups" />
620      </nav>
621    </template>
622    <template #nav-screen-content-after>
623      <NolebaseEnhancedReadabilitiesScreenMenu />
624    </template>
625
626    <template #nav-bar-title-before>
627      <span
628        v-if="isHome"
629        class="home-menu-btn"
630        role="button"
631        tabindex="0"
632        aria-label="Menu"
633        @click.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
634        @keydown.enter.prevent.stop="homeSidebarOpen = !homeSidebarOpen"
635      >
636        <span class="vpi-align-left home-menu-icon" />
637      </span>
638    </template>
639  </Layout>
640</template>