-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathDarkToggle.vue
68 lines (62 loc) · 1.61 KB
/
DarkToggle.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<script setup lang="ts">
import { useDark, useToggle } from '@vueuse/core'
import { nextTick } from 'vue'
const props = withDefaults(defineProps<{
isDark?: boolean
animation?: boolean
animationDuration?: number
}>(), {
isDark: false,
animation: true,
animationDuration: 400,
})
const isDark = useDark()
const toggleDark = useToggle(isDark)
const isAppearanceTransition = !!document.startViewTransition
&& !window.matchMedia('(prefers-reduced-motion: reduce)').matches
/**
* Credit to [@hooray](https://github.com/hooray)
* @see https://github.com/vuejs/vitepress/pull/2347
*/
function toggle(event?: MouseEvent) {
if (!isAppearanceTransition || !event || !props.animation) {
toggleDark()
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: isDark.value
? [...clipPath].reverse()
: clipPath,
},
{
duration: props.animationDuration,
easing: 'ease-in',
pseudoElement: isDark.value
? '::view-transition-old(root)'
: '::view-transition-new(root)',
},
)
})
}
</script>
<template>
<span class="$ui-dark-toggle-vtr">
<slot v-bind="{ isDark, toggle }" />
</span>
</template>