Skip to content

Commit

Permalink
Fix #143 - Put 'dark' class on html as soon as possible (#144)
Browse files Browse the repository at this point in the history
* Put 'dark' class on html as soon as possible

* Some fixes

* Addess suggestion
  • Loading branch information
allevo authored Oct 1, 2024
1 parent 29d27a3 commit 3a7cd4c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
15 changes: 15 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<html lang="en">
<head>
<script
type="application/javascript"
id="dark-mode-detection"
dangerouslySetInnerHTML={{ __html: initDarkModeDetection }}
></script>
<meta property="og:title" content="Rustcrab" />
<meta
property="og:description"
Expand Down
12 changes: 3 additions & 9 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,12 @@ export default function Header() {
const [starsCount, setStarsCount] = useState<number | null>(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);
};
Expand Down

0 comments on commit 3a7cd4c

Please sign in to comment.