File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change
1
+ <button data-theme-toggler class =" text-sky-600 underline" >Toggle theme</button >
2
+
3
+ <script is:inline >
4
+ const htmlEl = document.querySelector('html')
5
+ const theme = (() => {
6
+ if (localStorage?.getItem('theme')) {
7
+ return localStorage.getItem('theme')
8
+ }
9
+ if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
10
+ return 'dark'
11
+ }
12
+ return 'light'
13
+ })()
14
+
15
+ if (theme === 'light') {
16
+ htmlEl.classList.remove('dark')
17
+ } else {
18
+ htmlEl.classList.add('dark')
19
+ }
20
+
21
+ localStorage?.setItem('theme', theme)
22
+
23
+ const handleToggleClick = () => {
24
+ const element = htmlEl
25
+ element.classList.toggle('dark')
26
+
27
+ const isDark = element.classList.contains('dark')
28
+ localStorage?.setItem('theme', isDark ? 'dark' : 'light')
29
+ }
30
+
31
+ document.querySelector('[data-theme-toggler]').addEventListener('click', handleToggleClick)
32
+ </script >
Original file line number Diff line number Diff line change 2
2
import Link from ' ../components/Link.astro'
3
3
import IconGitHub from ' ../components/IconGitHub.astro'
4
4
import IconTwitter from ' ../components/IconTwitter.astro'
5
+ import ThemeToggle from ' ../components/ThemeToggle.astro'
5
6
6
7
interface Props {
7
8
title? : string
@@ -71,7 +72,7 @@ const { title } = Astro.props
71
72
View source code
72
73
</Link >{ ' ' }
73
74
|{ ' ' }
74
- <button class = " text-sky-600 underline " > Toggle theme</ button >
75
+ <ThemeToggle / >
75
76
</footer >
76
77
</body >
77
78
</html >
You can’t perform that action at this time.
0 commit comments