File size: 2,052 Bytes
716c855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class ThemeToggle extends HTMLElement {
  connectedCallback() {
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: inline-block;
          cursor: pointer;
        }
        .toggle-container {
          display: flex;
          align-items: center;
          gap: 0.5rem;
        }
        .toggle-switch {
          position: relative;
          width: 44px;
          height: 24px;
          background: #e2e8f0;
          border-radius: 12px;
          transition: background 0.3s;
        }
        .toggle-switch::after {
          content: '';
          position: absolute;
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: white;
          top: 2px;
          left: 2px;
          transition: transform 0.3s;
        }
        :host([dark]) .toggle-switch {
          background: #4a5568;
        }
        :host([dark]) .toggle-switch::after {
          transform: translateX(20px);
        }
        .icon {
          width: 16px;
          height: 16px;
        }
      </style>
      <div class="toggle-container">
        <i data-feather="sun" class="icon"></i>
        <div class="toggle-switch"></div>
        <i data-feather="moon" class="icon"></i>
      </div>
    `;

    this.addEventListener('click', this.toggleTheme);
    this.checkTheme();
  }

  checkTheme() {
    if (document.documentElement.getAttribute('data-theme') === 'dark') {
      this.setAttribute('dark', '');
    }
  }

  toggleTheme() {
    const isDark = this.hasAttribute('dark');
    if (isDark) {
      document.documentElement.setAttribute('data-theme', 'light');
      this.removeAttribute('dark');
    } else {
      document.documentElement.setAttribute('data-theme', 'dark');
      this.setAttribute('dark', '');
    }
    this.updateTheme();
  }

  updateTheme() {
    const isDark = this.hasAttribute('dark');
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
  }
}

customElements.define('theme-toggle', ThemeToggle);