Persist theme before hydration
This commit is contained in:
@@ -26,14 +26,13 @@ export function ClawThemeSwitcher() {
|
||||
const ActiveIcon = activeOption.icon;
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem(THEME_STORAGE_KEY);
|
||||
const initialMode = isThemeMode(stored) ? stored : "system";
|
||||
const initialMode = readStoredThemeMode();
|
||||
setMode(initialMode);
|
||||
applyTheme(initialMode);
|
||||
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = () => {
|
||||
if (window.localStorage.getItem(THEME_STORAGE_KEY) === "system") {
|
||||
if (readStoredThemeMode() === "system") {
|
||||
applyTheme("system");
|
||||
}
|
||||
};
|
||||
@@ -97,3 +96,8 @@ function applyTheme(mode: ThemeMode) {
|
||||
function isThemeMode(value: string | null): value is ThemeMode {
|
||||
return value === "light" || value === "dark" || value === "system";
|
||||
}
|
||||
|
||||
function readStoredThemeMode(): ThemeMode {
|
||||
const stored = window.localStorage.getItem(THEME_STORAGE_KEY);
|
||||
return isThemeMode(stored) ? stored : "system";
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh-CN" suppressHydrationWarning>
|
||||
<head>
|
||||
<script src="/theme-init.js" />
|
||||
</head>
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
(() => {
|
||||
try {
|
||||
const stored = window.localStorage.getItem("claw.theme");
|
||||
const mode =
|
||||
stored === "light" || stored === "dark" || stored === "system"
|
||||
? stored
|
||||
: "system";
|
||||
const prefersDark = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)",
|
||||
).matches;
|
||||
const shouldUseDark = mode === "dark" || (mode === "system" && prefersDark);
|
||||
document.documentElement.classList.toggle("dark", shouldUseDark);
|
||||
} catch (_) {}
|
||||
})();
|
||||
Reference in New Issue
Block a user