feat: theme follows system preference by default + fix dark mode FOUC
- getTheme: manual localStorage override first, else prefers-color-scheme - layout: inline head script sets data-theme before first paint (no white flash in dark mode on loading screen) - AppProvider: listen for system theme change when user hasn't overridden
This commit is contained in:
1 parent
156e178160
commit
83d270eada
3 files changed
+36
-2
No files matched your search
@@ -11,6 +11,22 @@ export const metadata = {
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html lang="zh-CN" suppressHydrationWarning>
|
||||
<head>
|
||||
{/* 首帧前同步主题,避免深色模式闪白(FOUC):手动设置优先,否则跟随系统 */}
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `(function(){
|
||||
try {
|
||||
var t = localStorage.getItem('forumlify-theme');
|
||||
if (!t) {
|
||||
t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
|
||||
}
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
} catch (e) {}
|
||||
})();`,
|
||||
}}
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<CustomCssLoader />
|
||||
{children}
|
||||
|
||||
@@ -37,6 +37,19 @@ export default function AppProvider({ children }) {
|
||||
const t = getTheme();
|
||||
setThemeState(t);
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
// 系统主题变化时跟随(仅当用户未手动设置过)
|
||||
const mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
|
||||
if (mq && mq.addEventListener) {
|
||||
const onSysChange = () => {
|
||||
if (!localStorage.getItem('forumlify-theme')) {
|
||||
const next = mq.matches ? 'dark' : 'light';
|
||||
setThemeState(next);
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
}
|
||||
};
|
||||
mq.addEventListener('change', onSysChange);
|
||||
return () => mq.removeEventListener('change', onSysChange);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
|
||||
+7
-2
@@ -195,8 +195,13 @@ export function generateCaptcha() {
|
||||
return { question: a + ' ' + op + ' ' + b + ' = ?', answer: op === '+' ? a + b : a - b };
|
||||
}
|
||||
|
||||
// 主题
|
||||
// 主题:手动设置优先,否则跟随系统偏好
|
||||
export function getTheme() {
|
||||
if (typeof window === 'undefined') return 'light';
|
||||
return localStorage.getItem('forumlify-theme') || 'light';
|
||||
const saved = localStorage.getItem('forumlify-theme');
|
||||
if (saved) return saved;
|
||||
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
return 'dark';
|
||||
}
|
||||
return 'light';
|
||||
}
|
||||
Reference in new issue
Block a user