From 3f3ae167e9d95f5bceb4e3aff491ced77e4a7ffa Mon Sep 17 00:00:00 2001 From: ernolf Date: Fri, 25 Oct 2024 20:30:30 +0200 Subject: [PATCH] fix(ui): split theme & icon load to prevent flicker, errors Signed-off-by: ernolf --- php/public/toggle-dark-mode.js | 19 +++++++++++++++---- php/templates/layout.twig | 2 +- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/php/public/toggle-dark-mode.js b/php/public/toggle-dark-mode.js index 773a9f18..9df54287 100644 --- a/php/public/toggle-dark-mode.js +++ b/php/public/toggle-dark-mode.js @@ -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); diff --git a/php/templates/layout.twig b/php/templates/layout.twig index cad5ae7a..56e4ee6b 100644 --- a/php/templates/layout.twig +++ b/php/templates/layout.twig @@ -15,7 +15,7 @@