feat: implement theme toggle functionality with useTheme composable

This commit is contained in:
2025-09-02 21:48:19 +02:00
parent 8f5ae6bf7e
commit 6641846a8b
3 changed files with 77 additions and 60 deletions

View File

@@ -1,64 +1,6 @@
<script lang="ts" setup>
const colorMode = useColorMode()
const { t } = useI18n({ useScope: 'local' })
const isDark = computed({
get: () => colorMode.value === 'dark',
set: (val: boolean) => {
colorMode.preference = val ? 'dark' : 'light'
},
})
const dark = computed({
get: () => colorMode.value === 'dark',
set: () => {},
})
function toggleDark(event: MouseEvent | { clientX: number, clientY: number }) {
// @ts-expect-error experimental API
const isAppearanceTransition = document.startViewTransition
&& !window.matchMedia('(prefers-reduced-motion: reduce)').matches
if (!isAppearanceTransition) {
isDark.value = !isDark.value
return
}
const x = event.clientX
const y = event.clientY
const endRadius = Math.hypot(
Math.max(x, innerWidth - x),
Math.max(y, innerHeight - y),
)
const transition = document.startViewTransition(async () => {
isDark.value = !isDark.value
await nextTick()
})
transition.ready
.then(() => {
const clipPath = [
`circle(0px at ${x}px ${y}px)`,
`circle(${endRadius}px at ${x}px ${y}px)`,
]
document.documentElement.animate(
{
clipPath: colorMode.value === 'dark'
? [...clipPath].reverse()
: clipPath,
},
{
duration: 400,
easing: 'ease-out',
pseudoElement: colorMode.value === 'dark'
? '::view-transition-old(root)'
: '::view-transition-new(root)',
},
)
})
}
defineShortcuts({
t: () => toggleDark({ clientX: window.innerWidth, clientY: 0 }),
})
const { dark, toggleDark } = useTheme()
</script>
<template>