fix: prevent theme flash during page load (#688)

* Apply patch [skip ci]

* Apply patch [skip ci]

* Apply patch [skip ci]

* Apply patch [skip ci]

* Empty commit to trigger CI

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Brace Sproul <braceasproul@gmail.com>
This commit is contained in:
open-swe[bot] 2025-08-07 00:08:09 +00:00 • committed by GitHub
parent 8e461d7040
commit 164794d11f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 37 additions and 7 deletions

View file

@ -31,6 +31,32 @@ export default function RootLayout({
lang="en"
suppressHydrationWarning
>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme');
var root = document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
} else if (theme === 'light') {
root.classList.add('light');
} else if (theme === 'system' || !theme) {
var systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
root.classList.add(systemTheme);
}
} catch (e) {
// Fallback to light theme if there's any error
document.documentElement.classList.add('light');
}
})();
`,
}}
/>
</head>
<body className={inter.className}>
<ThemeProvider
defaultTheme="system"

View file

@ -40,16 +40,20 @@ export function ThemeProvider({
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove("light", "dark");
// Determine the target theme
let targetTheme: string;
if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
targetTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
root.classList.add(systemTheme);
} else {
root.classList.add(theme);
targetTheme = theme;
}
// Only apply theme if it's not already present
if (!root.classList.contains(targetTheme)) {
root.classList.remove("light", "dark");
root.classList.add(targetTheme);
}
}, [theme]);

View file

@ -1,4 +1,4 @@
import { useTheme } from "next-themes";
import { useTheme } from "@/components/theme-provider";
import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {