Spaces:
Running
Running
File size: 2,673 Bytes
e59e970 | 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 | class ThemeToggle extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.render();
this.setupEventListeners();
}
render() {
this.shadowRoot.innerHTML = `
<style>
.toggle-container {
position: fixed;
bottom: 2rem;
right: 2rem;
z-index: 50;
}
.toggle-btn {
background: var(--bg-color);
color: var(--text-color);
border: none;
border-radius: 50%;
width: 3rem;
height: 3rem;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
transition: all 0.3s ease;
}
.toggle-btn:hover {
transform: scale(1.1);
}
.toggle-btn:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);
}
</style>
<div class="toggle-container">
<button class="toggle-btn" id="themeToggle">
<i data-feather="moon"></i>
</button>
</div>
`;
}
setupEventListeners() {
const themeToggle = this.shadowRoot.getElementById('themeToggle');
// Check for saved theme preference or use system preference
const savedTheme = localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.classList.toggle('dark', savedTheme === 'dark');
// Set initial icon
this.updateIcon(themeToggle, savedTheme);
themeToggle.addEventListener('click', () => {
const isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
this.updateIcon(themeToggle, isDark ? 'dark' : 'light');
});
}
updateIcon(button, theme) {
const icon = button.querySelector('i');
if (theme === 'dark') {
icon.setAttribute('data-feather', 'sun');
} else {
icon.setAttribute('data-feather', 'moon');
}
feather.replace();
}
}
customElements.define('theme-toggle', ThemeToggle); |