Skip to content

Commit c65c52e

Browse files
committed
fix: toggle theme in vitepress
1 parent f7d3564 commit c65c52e

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/VuePreview.vue

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
import '@liting-yes/vue-repl/style.css'
33
import type { PreviewUpdateFlag, Store } from '@liting-yes/vue-repl'
44
import { ExtendEditorContainer, Preview, ReplStore, defaultMainFile, importMapFile } from '@liting-yes/vue-repl'
5-
import { computed, onMounted, provide, ref, toRef } from 'vue'
6-
import { useClipboard, useElementHover } from '@vueuse/core'
5+
import { computed, onMounted, provide, ref } from 'vue'
6+
import { useClipboard, useElementHover, useMutationObserver } from '@vueuse/core'
77
import Copy from './icons/Copy.vue'
88
import Copied from './icons/Copied.vue'
99
import UnfoldLess from './icons/UnfoldLess.vue'
@@ -49,7 +49,6 @@ const props = withDefaults(defineProps<Props>(), {
4949
useCode: '',
5050
},
5151
}),
52-
theme: 'light',
5352
hideMessageToggle: true,
5453
hideMessage: false,
5554
})
@@ -85,10 +84,24 @@ if (props.importMap) {
8584
8685
store.setFiles(files)
8786
87+
const theme = ref<'dark' | 'light'>()
88+
const themeComputed = computed(() => props.theme ?? theme.value)
8889
onMounted(() => {
8990
if (props.clearConsole)
9091
// eslint-disable-next-line no-console
9192
console.clear()
93+
94+
const rootEl = document?.querySelector('html')
95+
if (rootEl) {
96+
useMutationObserver(rootEl, (mutations) => {
97+
mutations.forEach((mutation) => {
98+
if (mutation.attributeName === 'class')
99+
theme.value = rootEl.classList?.contains('dark') ? 'dark' : 'light'
100+
})
101+
}, {
102+
attributes: true,
103+
})
104+
}
92105
})
93106
94107
const previewUpdateFlag = ref<PreviewUpdateFlag>('UPDATING')
@@ -102,7 +115,7 @@ provide('store', store)
102115
provide('autoresize', props.autoResize)
103116
provide('clear-console', props.clearConsole)
104117
provide('preview-options', props.previewOptions)
105-
provide('theme', toRef(props, 'theme'))
118+
provide('theme', themeComputed)
106119
107120
const { copy, copied } = useClipboard({ source: store.state.activeFile.code, legacy: true })
108121

0 commit comments

Comments
 (0)