class ThemeToggle extends HTMLElement {
constructor() {
super();
this.currentTheme = 'system';
}
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.render();
this.bindEvents();
this.loadSavedTheme();
}
render() {
this.shadowRoot.innerHTML = `
`;
}
bindEvents() {
this.shadowRoot.querySelectorAll('.theme-option').forEach(button => {
button.addEventListener('click', (e) => {
const theme = e.currentTarget.getAttribute('data-theme');
this.setTheme(theme);
});
});
}
loadSavedTheme() {
const savedTheme = localStorage.getItem('theme') || 'system';
this.setTheme(savedTheme);
}
setTheme(theme) {
this.currentTheme = theme;
// Update active state
this.shadowRoot.querySelectorAll('.theme-option').forEach(btn => {
btn.classList.remove('active');
});
this.shadowRoot.querySelector(`[data-theme="${theme}"]`).classList.add('active');
// Apply theme
const event = new CustomEvent('themechange', { detail: { theme } });
window.dispatchEvent(event);
// Update parent component
if (window.themeManager) {
window.themeManager.setTheme(theme);
}
}
static get observedAttributes() {
return ['current-theme'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'current-theme' && newValue) {
this.setTheme(newValue);
}
}
}
customElements.define('custom-theme-toggle', ThemeToggle);