62 lines
1.5 KiB
Vue

<template>
<div class="flex flex-row">
<img class="icon" :src="iconLightSrc">
<Toggle ref="toggle" class="mx-2" @change="toggleMode" />
<img class="icon" :src="iconDarkSrc">
</div>
</template>
<script>
import Toggle from '@/components/darkmode/Toggle'
export default {
name: 'DarkModeToggle',
components: {
Toggle
},
data () {
return {
iconLightSrc: '/icon/sun.svg',
iconDarkSrc: '/icon/moon.svg'
}
},
mounted () {
const initDarkMode = this.isDarkEnabled()
this.$refs.toggle.value = initDarkMode
this.updateTheme()
this.updateIcons(initDarkMode)
this.$emit('darkModeChange', initDarkMode)
},
methods: {
toggleMode (darkMode) {
localStorage.theme = darkMode ? 'dark' : 'light'
this.updateTheme()
this.updateIcons(darkMode)
this.$emit('darkModeChange', darkMode)
},
updateTheme () {
if (this.isDarkEnabled()) {
document.querySelector('html').classList.add('mode-dark')
} else {
document.querySelector('html').classList.remove('mode-dark')
}
},
isDarkEnabled () {
return (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches))
},
updateIcons (darkMode) {
this.iconDarkSrc = darkMode ? '/icon/moon-white.svg' : '/icon/moon.svg'
this.iconLightSrc = darkMode ? '/icon/sun-white.svg' : '/icon/sun.svg'
}
}
}
</script>
<style scoped>
.icon {
width: 24px;
height: 24px;
margin: auto;
}
</style>