docs/.vitepress/theme/components/Collapsible.vue
37 lines · 1155 bytes
1<script setup lang="ts">
2import { useEventListener } from '@vueuse/core'
3import { nextTick, onMounted, ref } from 'vue'
4
5defineProps<{ title?: string }>()
6
7const open = ref(false)
8const detailsRef = ref<HTMLDetailsElement | null>(null)
9
10function openForHash(hash: string) {
11 if (!hash || !detailsRef.value) return
12 const id = decodeURIComponent(hash).slice(1)
13 const target = id && document.getElementById(id)
14 if (!target || !detailsRef.value.contains(target)) return
15 open.value = true
16 nextTick(() => target.scrollIntoView({ block: 'start' }))
17}
18
19onMounted(() => openForHash(location.hash))
20useEventListener(window, 'hashchange', () => openForHash(location.hash))
21useEventListener(document, 'click', (e) => {
22 const link = (e.target as HTMLElement)?.closest?.<HTMLAnchorElement>('a[href*="#"]')
23 if (link?.hash) nextTick(() => openForHash(link.hash))
24}, { capture: true })
25</script>
26
27<template>
28 <details
29 ref="detailsRef"
30 class="details custom-block"
31 :open="open || undefined"
32 @toggle="open = ($event.target as HTMLDetailsElement).open"
33 >
34 <summary>{{ title || 'Details' }}</summary>
35 <slot />
36 </details>
37</template>