返回 slidev
CodeBlockWrapper.vue
根目录 / packages / client / builtin / CodeBlockWrapper.vue
1 <!--
2 Line highlighting for code blocks.
3 (auto transformed, you don't need to use this component directly)
4
5 Usage:
6
7 ```ts {1,3-5|2,4}
8 const your_code = 'here'
9 ```
10
11 Learn more: https://sli.dev/guide/syntax.html#line-highlighting
12 -->
13
14 <script setup lang="ts">
15 import type { PropType, Ref } from 'vue'
16 import { useClipboard } from '@vueuse/core'
17 import { computed, inject, onMounted, onUnmounted, ref, watchEffect } from 'vue'
18 import { CLASS_VCLICK_HIDDEN, CLICKS_MAX } from '../constants'
19 import { useSlideContext } from '../context'
20 import { configs } from '../env'
21 import TitleIcon from '../internals/TitleIcon.vue'
22 import { makeId, updateCodeHighlightRange } from '../logic/utils'
23
24 const props = defineProps({
25 ranges: {
26 type: Array as PropType<string[]>,
27 default: () => [],
28 },
29 finally: {
30 type: [String, Number],
31 default: 'last',
32 },
33 startLine: {
34 type: Number,
35 default: 1,
36 },
37 lines: {
38 type: Boolean,
39 default: configs.lineNumbers,
40 },
41 at: {
42 type: [String, Number],
43 default: '+1',
44 },
45 maxHeight: {
46 type: String,
47 default: undefined,
48 },
49 title: {
50 type: String,
51 default: '',
52 },
53 })
54 const { $frontmatter, $clicksContext: clicks } = useSlideContext()
55 const isCodeCopy = computed(() => $frontmatter?.codeCopy ?? configs.codeCopy)
56
57 const el = ref<HTMLDivElement>()
58 const id = makeId()
59
60 onUnmounted(() => {
61 clicks!.unregister(id)
62 })
63
64 watchEffect(() => {
65 el.value?.classList.toggle('slidev-code-line-numbers', props.lines)
66 })
67
68 onMounted(() => {
69 if (!clicks || !props.ranges?.length)
70 return
71
72 const clicksInfo = clicks.calculateSince(props.at, props.ranges.length - 1)
73 clicks.register(id, clicksInfo)
74
75 const index = computed(() => clicksInfo
76 ? Math.max(0, clicks.current - clicksInfo.start + 1)
77 : CLICKS_MAX)
78
79 const finallyRange = computed(() => {
80 return props.finally === 'last'
81 ? props.ranges.at(-1)
82 : props.finally.toString()
83 })
84
85 let hiddenByRange = false
86
87 watchEffect(() => {
88 if (!el.value)
89 return
90
91 let rangeStr = props.ranges[index.value] ?? finallyRange.value
92 const hide = rangeStr === 'hide'
93 // Only toggle the class when a `hide` range set it, so a click directive on the same element keeps control
94 if (hide || hiddenByRange) {
95 el.value.classList.toggle(CLASS_VCLICK_HIDDEN, hide)
96 hiddenByRange = hide
97 }
98 if (hide)
99 rangeStr = props.ranges[index.value + 1] ?? finallyRange.value
100
101 const pre = el.value.querySelector('.shiki')!
102 const lines = Array.from(pre.querySelectorAll('code > .line'))
103 const linesCount = lines.length
104
105 updateCodeHighlightRange(
106 rangeStr,
107 linesCount,
108 props.startLine,
109 no => [lines[no]],
110 )
111
112 // Scroll to the highlighted line if `maxHeight` is set
113 if (props.maxHeight) {
114 const highlightedEls = Array.from(pre.querySelectorAll('.line.highlighted')) as HTMLElement[]
115 const height = highlightedEls.reduce((acc, el) => el.offsetHeight + acc, 0)
116 if (height > el.value.offsetHeight) {
117 highlightedEls[0].scrollIntoView({ behavior: 'smooth', block: 'start' })
118 }
119 else if (highlightedEls.length > 0) {
120 const middleEl = highlightedEls[Math.round((highlightedEls.length - 1) / 2)]
121 middleEl.scrollIntoView({ behavior: 'smooth', block: 'center' })
122 }
123 }
124 })
125 })
126
127 const { copied, copy } = useClipboard()
128
129 function copyCode() {
130 const code = el.value?.querySelector('.slidev-code')?.textContent
131 if (code)
132 copy(code)
133 }
134
135 // code block title
136 const activeTitle = inject<Ref<string> | null>('activeTitle', null)
137
138 const isBlockTitleShow = computed(() => {
139 return activeTitle === null && props.title
140 })
141 </script>
142
143 <template>
144 <div
145 ref="el"
146 class="slidev-code-wrapper relative group"
147 :class="{
148 'slidev-code-line-numbers': props.lines,
149 'active': activeTitle === title,
150 }"
151 :style="{
152 'max-height': props.maxHeight,
153 'overflow-y': props.maxHeight ? 'scroll' : undefined,
154 '--start': props.startLine,
155 }"
156 :data-title="title"
157 >
158 <div v-if="isBlockTitleShow" class="slidev-code-block-title">
159 <TitleIcon :title="title" />
160 <div class="leading-1em">
161 {{ title.replace(/~([^~]+)~/g, '').trim() }}
162 </div>
163 </div>
164 <slot />
165 <button
166 v-if="isCodeCopy"
167 class="slidev-code-copy absolute right-0 transition opacity-0 group-hover:opacity-20 hover:!opacity-100"
168 :class="isBlockTitleShow ? 'top-10' : 'top-0'"
169 :title="copied ? 'Copied' : 'Copy'" @click="copyCode()"
170 >
171 <ph-check-circle v-if="copied" class="p-2 w-8 h-8" />
172 <ph-clipboard v-else class="p-2 w-8 h-8" />
173 </button>
174 </div>
175 </template>
176
176 lines Plain Text