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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
'use client';
import { cn } from '@/lib/utils';
import { cva } from 'class-variance-authority';
import { Airplay, Moon, Sun } from 'lucide-react';
import { motion } from 'motion/react';
import { useTheme } from 'next-themes';
import { type HTMLAttributes, useLayoutEffect, useState } from 'react';
const themes = [
{
key: 'light',
icon: Sun,
label: 'Light theme',
},
{
key: 'dark',
icon: Moon,
label: 'Dark theme',
},
{
key: 'system',
icon: Airplay,
label: 'System theme',
},
];
const itemVariants = cva(
'relative size-6.5 rounded-full p-1.5 text-fd-muted-foreground',
{
variants: {
active: {
true: 'text-fd-accent-foreground',
false: 'text-fd-muted-foreground',
},
},
},
);
type Theme = 'light' | 'dark' | 'system';
export function ThemeToggle({
className,
mode = 'light-dark',
...props
}: HTMLAttributes<HTMLDivElement> & {
mode?: 'light-dark' | 'light-dark-system';
}) {
const { setTheme, theme: currentTheme, resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
const container = cn(
'relative flex items-center rounded-full p-1 ring-1 ring-border',
className,
);
useLayoutEffect(() => {
setMounted(true);
}, []);
const handleChangeTheme = async (theme: Theme) => {
function update() {
setTheme(theme);
}
if (document.startViewTransition && theme !== resolvedTheme) {
document.documentElement.style.viewTransitionName = 'theme-transition';
await document.startViewTransition(update).finished;
document.documentElement.style.viewTransitionName = '';
} else {
update();
}
};
const value = mounted
? mode === 'light-dark'
? resolvedTheme
: currentTheme
: null;
return (
<div
className={container}
onClick={() => {
if (mode !== 'light-dark') return;
handleChangeTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
}}
data-theme-toggle=''
aria-label={mode === 'light-dark' ? 'Toggle Theme' : undefined}
{...props}
>
{themes.map(({ key, icon: Icon, label }) => {
const isActive = value === key;
if (mode === 'light-dark' && key === 'system') return;
return (
<button
type='button'
key={key}
className={itemVariants({ active: isActive })}
onClick={() => {
if (mode === 'light-dark') return;
handleChangeTheme(key as Theme);
}}
aria-label={label}
>
{isActive && (
<motion.div
layoutId='activeTheme'
className='absolute inset-0 rounded-full bg-accent'
transition={{
type: 'spring',
duration: mode === 'light-dark' ? 1.5 : 1,
}}
/>
)}
<Icon
className={'relative m-auto size-full'}
fill={'currentColor'}
/>
</button>
);
})}
</div>
);
}
|