95 lines
3.0 KiB
JavaScript
95 lines
3.0 KiB
JavaScript
/**
|
|
* Theme Toggle - Light/Dark Mode
|
|
* Persists user preference in localStorage
|
|
*/
|
|
|
|
class ThemeToggle {
|
|
constructor() {
|
|
this.STORAGE_KEY = 'quality-app-theme';
|
|
this.DARK_THEME = 'dark';
|
|
this.LIGHT_THEME = 'light';
|
|
this.init();
|
|
}
|
|
|
|
init() {
|
|
// Load saved theme or default to light
|
|
const savedTheme = localStorage.getItem(this.STORAGE_KEY) || this.LIGHT_THEME;
|
|
this.setTheme(savedTheme);
|
|
|
|
// Setup toggle button listener
|
|
this.setupToggleButton();
|
|
|
|
console.log('Theme initialized:', savedTheme);
|
|
}
|
|
|
|
setTheme(theme) {
|
|
const isDark = theme === this.DARK_THEME;
|
|
|
|
if (isDark) {
|
|
document.body.setAttribute('data-theme', 'dark');
|
|
document.documentElement.setAttribute('data-theme', 'dark');
|
|
localStorage.setItem(this.STORAGE_KEY, this.DARK_THEME);
|
|
console.log('Dark theme set');
|
|
} else {
|
|
document.body.setAttribute('data-theme', 'light');
|
|
document.documentElement.setAttribute('data-theme', 'light');
|
|
localStorage.setItem(this.STORAGE_KEY, this.LIGHT_THEME);
|
|
console.log('Light theme set');
|
|
}
|
|
|
|
// Update toggle button icon
|
|
this.updateToggleIcon(isDark);
|
|
}
|
|
|
|
getCurrentTheme() {
|
|
return document.body.getAttribute('data-theme') || this.LIGHT_THEME;
|
|
}
|
|
|
|
toggleTheme() {
|
|
const currentTheme = this.getCurrentTheme();
|
|
const newTheme = currentTheme === this.DARK_THEME ? this.LIGHT_THEME : this.DARK_THEME;
|
|
console.log('Toggling from', currentTheme, 'to', newTheme);
|
|
this.setTheme(newTheme);
|
|
}
|
|
|
|
setupToggleButton() {
|
|
const toggleBtn = document.getElementById('themeToggleBtn');
|
|
if (toggleBtn) {
|
|
toggleBtn.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
this.toggleTheme();
|
|
});
|
|
console.log('Theme toggle button setup complete');
|
|
} else {
|
|
console.error('Theme toggle button not found');
|
|
}
|
|
}
|
|
|
|
updateToggleIcon(isDark) {
|
|
const toggleBtn = document.getElementById('themeToggleBtn');
|
|
if (toggleBtn) {
|
|
const icon = toggleBtn.querySelector('i');
|
|
if (icon) {
|
|
if (isDark) {
|
|
icon.classList.remove('fa-moon');
|
|
icon.classList.add('fa-sun');
|
|
toggleBtn.setAttribute('title', 'Switch to Light Mode');
|
|
} else {
|
|
icon.classList.remove('fa-sun');
|
|
icon.classList.add('fa-moon');
|
|
toggleBtn.setAttribute('title', 'Switch to Dark Mode');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Initialize theme toggle when DOM is loaded
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
new ThemeToggle();
|
|
});
|
|
} else {
|
|
new ThemeToggle();
|
|
}
|