docs/.vitepress/theme/Layout.vue

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

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