web/src/components/form/ThemeSwitcher.svelte
91 lines · 2158 bytes
1<script lang="ts">
2 import { onMount } from 'svelte';
3 import FontAwesome from '@components/form/FontAwesome.svelte';
4
5 let theme = $state('dark');
6
7 onMount(() => {
8 theme = document.documentElement.dataset.theme || 'dark';
9 });
10
11 function toggleTheme(): void {
12 theme = theme === 'dark' ? 'light' : 'dark';
13 localStorage.setItem('theme', theme);
14 document.documentElement.dataset.theme = theme;
15 }
16</script>
17
18<button
19 class="theme-switcher"
20 onclick={toggleTheme}
21 aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
22>
23 <span class={`toggle ${theme}`}>
24 <span class="theme-icon"><FontAwesome iconName="themeDark" /></span>
25 <span class="theme-icon"><FontAwesome iconName="themeLight" /></span>
26 </span>
27</button>
28
29<style lang="scss">
30 .theme-switcher {
31 cursor: pointer;
32 display: inline-flex;
33 padding: var(--space-xs);
34 border: var(--border-heavy);
35 border-radius: var(--curve-lg);
36 background: var(--surface-line);
37 box-shadow: var(--shadow-sm);
38 transition: var(--transition-normal);
39
40 &:hover {
41 box-shadow: var(--shadow-sm-hover);
42 }
43 }
44
45 .toggle {
46 display: flex;
47 align-items: center;
48 justify-content: space-between;
49 gap: var(--space-sm);
50 width: 4rem;
51 height: 2rem;
52 padding: 0 var(--space-sm);
53 box-sizing: border-box;
54 position: relative;
55 background: var(--surface);
56 border-radius: var(--curve-lg);
57
58 &::before {
59 content: '';
60 position: absolute;
61 top: 50%;
62 left: var(--space-xs);
63 width: 1.6rem;
64 height: 1.6rem;
65 border-radius: 50%;
66 background: var(--accent-3);
67 transition: transform 0.3s ease;
68 transform: translateY(-50%);
69 }
70
71 &:not(.dark)::before {
72 transform: translate(2.2rem, -50%);
73 }
74 }
75
76 .theme-icon {
77 display: flex;
78 z-index: 1;
79 color: var(--foreground);
80 :global(svg) {
81 width: 1rem;
82 height: 1rem;
83 }
84 }
85
86 /* Whichever icon the knob sits under needs ink that reads on it */
87 .toggle.dark .theme-icon:first-child,
88 .toggle:not(.dark) .theme-icon:last-child {
89 color: var(--accent-3-fg);
90 }
91</style>