返回 slidev
Toc.vue
根目录 / packages / client / builtin / Toc.vue
1 <!--
2 Table Of content
3
4 `mode` can be either 'all', 'onlyCurrentTree' or 'onlySiblings'
5
6 Usage:
7
8 <Toc columns='2' maxDepth='3' mode='onlySiblings'/>
9 -->
10 <script setup lang='ts'>
11 import type { TocItem } from '@slidev/types'
12 import { computed } from 'vue'
13 import { useSlideContext } from '../context'
14 import TocList from './TocList.vue'
15
16 const props = withDefaults(
17 defineProps<{
18 columns?: string | number
19 listClass?: string | string[]
20 start?: string | number
21 listStyle?: string | string[]
22 maxDepth?: string | number
23 minDepth?: string | number
24 mode?: 'all' | 'onlyCurrentTree' | 'onlySiblings'
25 }>(),
26 {
27 columns: 1,
28 listClass: '',
29 start: 1,
30 listStyle: '',
31 maxDepth: Number.POSITIVE_INFINITY,
32 minDepth: 1,
33 mode: 'all',
34 },
35 )
36
37 const { $slidev } = useSlideContext()
38
39 function filterTreeDepth(tree: TocItem[], level = 1): TocItem[] {
40 if (level > Number(props.maxDepth)) {
41 return []
42 }
43 else if (level < Number(props.minDepth)) {
44 const activeItem = tree.find((item: TocItem) => item.active || item.activeParent)
45 return activeItem
46 ? filterTreeDepth(activeItem.children, level + 1)
47 : []
48 }
49 return tree
50 .map((item: TocItem) => ({
51 ...item,
52 children: filterTreeDepth(item.children, level + 1),
53 }))
54 }
55
56 function filterOnlyCurrentTree(tree: TocItem[]): TocItem[] {
57 return tree
58 .filter(
59 (item: TocItem) => item.active || item.activeParent || item.hasActiveParent,
60 )
61 .map((item: TocItem) => ({
62 ...item,
63 children: filterOnlyCurrentTree(item.children),
64 }))
65 }
66
67 function filterOnlySiblings(tree: TocItem[]): TocItem[] {
68 const treehasActiveItem = tree.some(
69 (item: TocItem) => item.active || item.activeParent || item.hasActiveParent,
70 )
71 return tree
72 .filter(() => treehasActiveItem)
73 .map((item: TocItem) => ({
74 ...item,
75 children: filterOnlySiblings(item.children),
76 }))
77 }
78
79 const toc = computed(() => {
80 const tree = $slidev?.nav.tocTree
81 if (!tree)
82 return []
83 let tocTree = filterTreeDepth(tree)
84 if (props.mode === 'onlyCurrentTree')
85 tocTree = filterOnlyCurrentTree(tocTree)
86 else if (props.mode === 'onlySiblings')
87 tocTree = filterOnlySiblings(tocTree)
88 return tocTree
89 })
90 </script>
91
92 <template>
93 <div class="slidev-toc" :style="`column-count:${columns}`">
94 <TocList
95 :level="1"
96 :start="start"
97 :list-style="listStyle"
98 :list="toc"
99 :list-class="listClass"
100 />
101 </div>
102 </template>
103
103 lines Plain Text