feat(public): add setting dark or light mode
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import ThemeToggle from "./ThemeToggle.vue"
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
function setLinks() {
|
||||
@@ -48,9 +50,10 @@ watch(
|
||||
<Separator orientation="vertical" class="h-4" />
|
||||
<!-- <BaseBreadcrumbCustom :links="links" /> -->
|
||||
</div>
|
||||
<div class="ml-auto">
|
||||
<slot />
|
||||
</div>
|
||||
<div class="ml-auto flex items-center gap-2">
|
||||
<slot />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { useTheme } from '~/composables/useTheme'
|
||||
const { theme, toggleTheme } = useTheme()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
@click="toggleTheme"
|
||||
class="ml-2 flex items-center rounded border px-2 py-1"
|
||||
:title="theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'"
|
||||
>
|
||||
<span v-if="theme === 'dark'"><Icon name="i-lucide-moon" class="h-4 w-4" /></span>
|
||||
<span v-else><Icon name="i-lucide-sun" class="h-4 w-4" /></span>
|
||||
</button>
|
||||
</template>
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ref, watchEffect } from 'vue'
|
||||
|
||||
const THEME_KEY = 'theme-mode'
|
||||
|
||||
export function useTheme() {
|
||||
const theme = ref<'light' | 'dark'>(getInitialTheme())
|
||||
|
||||
function getInitialTheme() {
|
||||
if (typeof window === 'undefined') return 'light'
|
||||
const persisted = localStorage.getItem(THEME_KEY)
|
||||
if (persisted === 'dark' || persisted === 'light') return persisted
|
||||
// fallback: system preference
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
function setTheme(newTheme: 'light' | 'dark') {
|
||||
theme.value = newTheme
|
||||
localStorage.setItem(THEME_KEY, newTheme)
|
||||
document.documentElement.classList.toggle('dark', newTheme === 'dark')
|
||||
}
|
||||
|
||||
function toggleTheme() {
|
||||
setTheme(theme.value === 'dark' ? 'light' : 'dark')
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
setTheme(theme.value)
|
||||
})
|
||||
|
||||
return { theme, toggleTheme }
|
||||
}
|
||||
Reference in New Issue
Block a user