92 lines
2.8 KiB
JavaScript
92 lines
2.8 KiB
JavaScript
/**
|
|
* Theme toggle functionality
|
|
* Handles light/dark mode switching
|
|
*/
|
|
|
|
(function() {
|
|
'use strict';
|
|
|
|
// Get theme preference from localStorage or system preference
|
|
function getThemePreference() {
|
|
const stored = localStorage.getItem('achille-press-theme');
|
|
if (stored) {
|
|
return stored;
|
|
}
|
|
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
}
|
|
|
|
// Set theme
|
|
function setTheme(theme) {
|
|
document.documentElement.setAttribute('data-theme', theme);
|
|
localStorage.setItem('achille-press-theme', theme);
|
|
|
|
// Update meta theme-color for mobile browsers
|
|
const metaThemeColor = document.querySelector('meta[name="theme-color"]');
|
|
if (metaThemeColor) {
|
|
metaThemeColor.setAttribute('content', theme === 'dark' ? '#1a1a1a' : '#ffffff');
|
|
}
|
|
}
|
|
|
|
// Toggle theme
|
|
function toggleTheme() {
|
|
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
|
|
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
|
setTheme(newTheme);
|
|
}
|
|
|
|
// Initialize theme on page load
|
|
function initTheme() {
|
|
const theme = getThemePreference();
|
|
setTheme(theme);
|
|
}
|
|
|
|
// Setup theme toggle button
|
|
function setupThemeToggle() {
|
|
const themeToggle = document.querySelector('.theme-toggle');
|
|
if (themeToggle) {
|
|
themeToggle.addEventListener('click', toggleTheme);
|
|
|
|
// Add keyboard support
|
|
themeToggle.addEventListener('keydown', function(e) {
|
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
e.preventDefault();
|
|
toggleTheme();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Listen for system theme changes
|
|
function setupSystemThemeListener() {
|
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
|
mediaQuery.addListener(function(e) {
|
|
// Only update if user hasn't manually set a preference
|
|
if (!localStorage.getItem('achille-press-theme')) {
|
|
setTheme(e.matches ? 'dark' : 'light');
|
|
}
|
|
});
|
|
}
|
|
|
|
// Initialize everything when DOM is ready
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
initTheme();
|
|
setupThemeToggle();
|
|
setupSystemThemeListener();
|
|
});
|
|
} else {
|
|
initTheme();
|
|
setupThemeToggle();
|
|
setupSystemThemeListener();
|
|
}
|
|
|
|
// Add meta theme-color if it doesn't exist
|
|
if (!document.querySelector('meta[name="theme-color"]')) {
|
|
const meta = document.createElement('meta');
|
|
meta.name = 'theme-color';
|
|
meta.content = '#ffffff';
|
|
document.head.appendChild(meta);
|
|
}
|
|
|
|
})();
|