Skip to content

Commit 20b2fb6

Browse files
authored
perf(code-block): debounce highlight updates with useDebounceFn (#56)
1 parent 0e3602d commit 20b2fb6

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

packages/elements/src/code-block/CodeBlock.vue

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import type { BundledLanguage } from 'shiki'
33
import type { HTMLAttributes } from 'vue'
44
import { cn } from '@repo/shadcn-vue/lib/utils'
5-
import { reactiveOmit } from '@vueuse/core'
5+
import { reactiveOmit, useDebounceFn } from '@vueuse/core'
66
import { computed, onBeforeUnmount, provide, ref, watch } from 'vue'
77
import { CodeBlockKey } from './context'
88
import { highlightCode } from './utils'
@@ -31,23 +31,27 @@ provide(CodeBlockKey, {
3131
let requestId = 0
3232
let isUnmounted = false
3333
34-
watch(
35-
() => [props.code, props.language, props.showLineNumbers] as const,
36-
async ([code, language, showLineNumbers]) => {
37-
requestId += 1
38-
const currentId = requestId
34+
const updateHighlight = useDebounceFn(async (code: string, language: BundledLanguage, showLineNumbers: boolean) => {
35+
requestId += 1
36+
const currentId = requestId
3937
40-
try {
41-
const [light, dark] = await highlightCode(code, language, showLineNumbers)
38+
try {
39+
const [light, dark] = await highlightCode(code, language, showLineNumbers)
4240
43-
if (currentId === requestId && !isUnmounted) {
44-
html.value = light
45-
darkHtml.value = dark
46-
}
47-
}
48-
catch (error) {
49-
console.error('[CodeBlock] highlight failed', error)
41+
if (currentId === requestId && !isUnmounted) {
42+
html.value = light
43+
darkHtml.value = dark
5044
}
45+
}
46+
catch (error) {
47+
console.error('[CodeBlock] highlight failed', error)
48+
}
49+
}, 100)
50+
51+
watch(
52+
() => [props.code, props.language, props.showLineNumbers] as const,
53+
([code, language, showLineNumbers]) => {
54+
updateHighlight(code, language, showLineNumbers)
5155
},
5256
{ immediate: true },
5357
)

0 commit comments

Comments
 (0)