|
1 | | -import { useCallback, useSyncExternalStore } from 'react'; |
| 1 | +import { useReducer } from 'react'; |
2 | 2 |
|
3 | | -function getIsDark() { |
4 | | - return document.documentElement.classList.contains('dark'); |
5 | | -} |
| 3 | +export function ThemeToggle() { |
| 4 | + const [, forceUpdate] = useReducer((x: number) => x + 1, 0); |
| 5 | + const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark'); |
6 | 6 |
|
7 | | -function subscribe(callback: () => void) { |
8 | | - const observer = new MutationObserver(callback); |
9 | | - observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] }); |
10 | | - return () => observer.disconnect(); |
11 | | -} |
| 7 | + const toggle = () => { |
| 8 | + const nowDark = document.documentElement.classList.contains('dark'); |
| 9 | + const next = !nowDark; |
12 | 10 |
|
13 | | -function applyTheme(dark: boolean) { |
14 | | - if (dark) { |
15 | | - document.documentElement.classList.add('dark'); |
16 | | - } else { |
17 | | - document.documentElement.classList.remove('dark'); |
18 | | - } |
19 | | - localStorage.setItem('theme', dark ? 'dark' : 'light'); |
20 | | - const meta = document.querySelector('meta[name="theme-color"]'); |
21 | | - if (meta) meta.setAttribute('content', dark ? '#111110' : '#fafaf9'); |
22 | | -} |
| 11 | + document.documentElement.classList.toggle('dark', next); |
| 12 | + localStorage.setItem('theme', next ? 'dark' : 'light'); |
23 | 13 |
|
24 | | -export function ThemeToggle() { |
25 | | - const isDark = useSyncExternalStore(subscribe, getIsDark); |
| 14 | + const meta = document.querySelector('meta[name="theme-color"]'); |
| 15 | + if (meta) meta.setAttribute('content', next ? '#111110' : '#fafaf9'); |
26 | 16 |
|
27 | | - const toggle = useCallback(() => { |
28 | | - applyTheme(!getIsDark()); |
29 | | - }, []); |
| 17 | + // Force re-render to update icon |
| 18 | + forceUpdate(); |
| 19 | + }; |
30 | 20 |
|
31 | 21 | return ( |
32 | 22 | <button |
|
0 commit comments