File size: 1,970 Bytes
fee9c1e
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee9c1e
 
 
 
 
 
 
 
 
 
fef84f3
fee9c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<button id="theme-toggle" aria-label="Toggle color theme">
  <svg class="icon light" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">
    <circle cx="12" cy="12" r="5"/>
    <g stroke="currentColor" stroke-width="2" stroke-linecap="round">
      <line x1="12" y1="1" x2="12" y2="4"/>
      <line x1="12" y1="20" x2="12" y2="23"/>
      <line x1="1" y1="12" x2="4" y2="12"/>
      <line x1="20" y1="12" x2="23" y2="12"/>
      <line x1="4.22" y1="4.22" x2="6.34" y2="6.34"/>
      <line x1="17.66" y1="17.66" x2="19.78" y2="19.78"/>
      <line x1="4.22" y1="19.78" x2="6.34" y2="17.66"/>
      <line x1="17.66" y1="6.34" x2="19.78" y2="4.22"/>
    </g>
  </svg>
  <svg class="icon dark" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">
    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
  </svg>
  <script>
    const btn = document.getElementById('theme-toggle');
    const media = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
    const prefersDark = media && media.matches;
    const saved = localStorage.getItem('theme'); // 'light' | 'dark' | null

    const apply = (mode) => {
      document.documentElement.dataset.theme = mode;
    };

    // Initial mode: default to light, then use localStorage, else system
    apply(saved || (prefersDark ? 'dark' : 'light'));

    // If user hasn't chosen manually, follow system changes
    if (!saved && media) {
      const syncWithSystem = (e) => apply(e.matches ? 'dark' : 'light');
      if (media.addEventListener) media.addEventListener('change', syncWithSystem);
      else if (media.addListener) media.addListener(syncWithSystem);
    }

    btn.addEventListener('click', () => {
      const next = (document.documentElement.dataset.theme === 'dark') ? 'light' : 'dark';
      localStorage.setItem('theme', next);
      apply(next);
    });
  </script>
</button>