Skip to content

Commit

Permalink
fix(ui): split theme & icon load to prevent flicker, errors
Browse files Browse the repository at this point in the history
Signed-off-by: ernolf <raphael.gradenwitz@googlemail.com>
  • Loading branch information
ernolf committed Oct 25, 2024
1 parent a0ce2c1 commit 3f3ae16
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
19 changes: 15 additions & 4 deletions php/public/toggle-dark-mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,28 @@ function toggleTheme() {
themeIcon.textContent = newTheme === 'dark' ? '☀️' : '🌙'; // Switch between moon and sun icons
}

// Function to apply saved theme from localStorage
function applySavedTheme() {
// Function to immediately apply saved theme without icon update
function applySavedThemeImmediately() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
} else {
document.documentElement.removeAttribute('data-theme'); // Default to light theme
}
}

// Function to apply theme-icon update
function setThemeIcon() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.getElementById('theme-icon').textContent = '☀️'; // Sun icon for dark mode
} else {
document.documentElement.removeAttribute('data-theme'); // Default to light theme (no data-theme)
document.getElementById('theme-icon').textContent = '🌙'; // Moon icon for light mode
}
}

// Immediately apply the saved theme to avoid flickering
applySavedThemeImmediately();

// Apply theme when the page loads
document.addEventListener('DOMContentLoaded', applySavedTheme);
document.addEventListener('DOMContentLoaded', setThemeIcon);
2 changes: 1 addition & 1 deletion php/templates/layout.twig
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<div class="loader"></div>
</div>
<button id="theme-toggle" onclick="toggleTheme()">
<span id="theme-icon">🌙</span>
<span id="theme-icon"></span>
</button>
</body>
</html>

0 comments on commit 3f3ae16

Please sign in to comment.