From 3a7cd4ccc9d7568388c779002d1f86e1835d317c Mon Sep 17 00:00:00 2001 From: Tommaso Allevi Date: Tue, 1 Oct 2024 19:14:49 +0200 Subject: [PATCH] Fix #143 - Put 'dark' class on html as soon as possible (#144) * Put 'dark' class on html as soon as possible * Some fixes * Addess suggestion --- src/app/layout.tsx | 15 +++++++++++++++ src/components/Header.tsx | 12 +++--------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/app/layout.tsx b/src/app/layout.tsx index f615869..07da032 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -14,9 +14,24 @@ export default function RootLayout({ }: Readonly<{ children: React.ReactNode; }>) { + const initDarkModeDetection = ` +(function () { +const isDarkModePreferred = window.matchMedia('(prefers-color-scheme: dark)').matches; +const themeChosen = localStorage.theme; +if ((!themeChosen && isDarkModePreferred) || themeChosen === "dark") { + document.documentElement.classList.add("dark"); + localStorage.theme = 'dark'; +} +})()`; + return ( + (null); useEffect(() => { - if ( - localStorage.theme === "dark" || - (!("theme" in localStorage) && - window.matchMedia("(prefers-color-scheme: dark)").matches) - ) { - document.documentElement.classList.add("dark"); + if (localStorage.theme === "dark") { setDarkMode(true); - } else { - document.documentElement.classList.remove("dark"); - setDarkMode(false); } + }, []); + useEffect(() => { const handleScroll = () => { setIsScrolled(window.scrollY > 0); };