|
2 | 2 | import type { BundledLanguage } from 'shiki' |
3 | 3 | import type { HTMLAttributes } from 'vue' |
4 | 4 | import { cn } from '@repo/shadcn-vue/lib/utils' |
5 | | -import { reactiveOmit } from '@vueuse/core' |
| 5 | +import { reactiveOmit, useDebounceFn } from '@vueuse/core' |
6 | 6 | import { computed, onBeforeUnmount, provide, ref, watch } from 'vue' |
7 | 7 | import { CodeBlockKey } from './context' |
8 | 8 | import { highlightCode } from './utils' |
@@ -31,23 +31,27 @@ provide(CodeBlockKey, { |
31 | 31 | let requestId = 0 |
32 | 32 | let isUnmounted = false |
33 | 33 |
|
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 |
39 | 37 |
|
40 | | - try { |
41 | | - const [light, dark] = await highlightCode(code, language, showLineNumbers) |
| 38 | + try { |
| 39 | + const [light, dark] = await highlightCode(code, language, showLineNumbers) |
42 | 40 |
|
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 |
50 | 44 | } |
| 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) |
51 | 55 | }, |
52 | 56 | { immediate: true }, |
53 | 57 | ) |
|
0 commit comments