fixed:自定义主题应用所有人

This commit is contained in:
djteang 2025-09-23 09:20:31 +08:00
parent 3457a7c565
commit 7707ba5414
4 changed files with 127 additions and 56 deletions

View File

@ -1,38 +0,0 @@
// 主题初始化脚本 - 立即执行,避免主题闪烁
(function () {
try {
// 应用主题函数
function applyTheme(themeId, css) {
const html = document.documentElement;
// 移除所有主题属性
html.removeAttribute('data-theme');
// 应用主题
if (themeId !== 'default') {
html.setAttribute('data-theme', themeId);
}
// 应用自定义CSS
if (css) {
let customStyleEl = document.getElementById('custom-theme-css');
if (!customStyleEl) {
customStyleEl = document.createElement('style');
customStyleEl.id = 'custom-theme-css';
document.head.appendChild(customStyleEl);
}
customStyleEl.textContent = css;
}
}
// 应用默认主题避免闪烁等待GlobalThemeLoader加载全站配置
applyTheme('default', '');
console.log('主题初始化完成,等待加载全站配置');
// 注意GlobalThemeLoader会在React组件挂载后加载并应用全站主题配置
} catch (error) {
console.error('主题初始化失败:', error);
}
})();

View File

@ -6,6 +6,7 @@ import { Inter } from 'next/font/google';
import './globals.css';
import { getConfig } from '@/lib/config';
import { db } from '@/lib/db';
import { GlobalErrorIndicator } from '../components/GlobalErrorIndicator';
import { SiteProvider } from '../components/SiteProvider';
@ -43,6 +44,24 @@ export default async function RootLayout({
}) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
// 预先获取主题配置
let themeConfig = {
defaultTheme: 'default',
customCSS: '',
allowUserCustomization: true
};
try {
if (storageType !== 'localstorage') {
const adminConfig = await db.getAdminConfig();
if (adminConfig?.ThemeConfig) {
themeConfig = adminConfig.ThemeConfig;
}
}
} catch (error) {
console.error('服务端获取主题配置失败:', error);
}
let siteName = process.env.NEXT_PUBLIC_SITE_NAME || 'OrangeTV';
let announcement =
process.env.ANNOUNCEMENT ||
@ -94,6 +113,7 @@ export default async function RootLayout({
CUSTOM_CATEGORIES: customCategories,
FLUID_SEARCH: fluidSearch,
REQUIRE_DEVICE_CODE: requireDeviceCode,
THEME_CONFIG: themeConfig,
};
return (
@ -112,8 +132,60 @@ export default async function RootLayout({
}}
/>
{/* 主题初始化脚本 - 立即执行避免主题闪烁 */}
<script src="/theme-init.js" />
{/* 主题初始化脚本 - 内联执行,确保在生产环境中立即应用主题 */}
{/* eslint-disable-next-line @next/next/no-sync-scripts */}
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
console.log('开始初始化主题...');
// 获取预设的主题配置
const themeConfig = window.RUNTIME_CONFIG?.THEME_CONFIG || {
defaultTheme: 'default',
customCSS: ''
};
console.log('服务端主题配置:', themeConfig);
// 应用主题函数
function applyTheme(themeId, css) {
const html = document.documentElement;
// 移除所有主题属性
html.removeAttribute('data-theme');
// 应用主题
if (themeId !== 'default') {
html.setAttribute('data-theme', themeId);
}
// 应用自定义CSS
if (css) {
let customStyleEl = document.getElementById('custom-theme-css');
if (!customStyleEl) {
customStyleEl = document.createElement('style');
customStyleEl.id = 'custom-theme-css';
document.head.appendChild(customStyleEl);
}
customStyleEl.textContent = css;
}
}
// 立即应用服务端主题配置
applyTheme(themeConfig.defaultTheme, themeConfig.customCSS);
console.log('主题已初始化:', themeConfig.defaultTheme);
} catch (error) {
console.error('主题初始化失败:', error);
// 失败时应用默认主题
document.documentElement.removeAttribute('data-theme');
}
})();
`,
}}
/>
</head>
<body
className={`${inter.className} min-h-screen bg-white text-gray-900 dark:bg-black dark:text-gray-200`}

View File

@ -2,31 +2,44 @@
import { useEffect } from 'react';
// 全局主题加载器组件
// 全局主题加载器组件 - 作为服务端主题配置的同步和备份机制
const GlobalThemeLoader = () => {
useEffect(() => {
const loadGlobalTheme = async () => {
const syncGlobalTheme = async () => {
try {
// 获取全局主题配置
// 检查是否已有服务端预设的主题配置
const runtimeConfig = (window as any).RUNTIME_CONFIG;
const serverThemeConfig = runtimeConfig?.THEME_CONFIG;
console.log('检查服务端主题配置:', serverThemeConfig);
if (serverThemeConfig) {
// 服务端已经应用了主题配置,检查是否需要同步更新
console.log('服务端主题配置已存在,无需重新加载');
return;
}
// 如果没有服务端配置则从API获取备用方案
console.log('未检测到服务端主题配置尝试从API加载...');
const response = await fetch('/api/theme');
const result = await response.json();
console.log('获取到全站主题配置:', result);
if (result.success && result.data) {
const { defaultTheme, customCSS } = result.data;
console.log('从API获取到主题配置:', { defaultTheme, customCSS });
console.log('加载全站主题配置:', { defaultTheme, customCSS });
// 直接应用全站配置
// 应用从API获取的配置
applyTheme(defaultTheme, customCSS);
console.log('已应用全站主题:', defaultTheme);
console.log('已应用API主题配置:', defaultTheme);
}
} catch (error) {
console.error('加载全站主题配置失败:', error);
// 失败时使用默认设置
applyTheme('default', '');
console.log('加载配置失败,使用默认主题');
console.error('同步全站主题配置失败:', error);
// 失败时检查当前HTML状态如果没有主题则应用默认
const html = document.documentElement;
if (!html.hasAttribute('data-theme')) {
applyTheme('default', '');
console.log('应用默认主题作为备用');
}
}
};
@ -52,8 +65,12 @@ const GlobalThemeLoader = () => {
customStyleEl.textContent = css;
};
// 立即加载,不延迟
loadGlobalTheme();
// 稍作延迟确保DOM完全加载后再同步
const timer = setTimeout(() => {
syncGlobalTheme();
}, 100);
return () => clearTimeout(timer);
}, []);
return null; // 这是一个逻辑组件,不渲染任何内容

View File

@ -280,6 +280,18 @@ const ThemeManager = ({ showAlert, role }: ThemeManagerProps) => {
// 加载全局主题配置
const loadGlobalThemeConfig = async () => {
try {
// 优先使用运行时配置中的主题配置
const runtimeConfig = (window as any).RUNTIME_CONFIG;
const serverThemeConfig = runtimeConfig?.THEME_CONFIG;
if (serverThemeConfig) {
console.log('使用服务端预设的主题配置:', serverThemeConfig);
setGlobalThemeConfig(serverThemeConfig);
return serverThemeConfig;
}
// 如果没有服务端配置则从API获取
console.log('服务端无主题配置从API获取...');
const response = await fetch('/api/theme');
const result = await response.json();
if (result.success) {
@ -307,9 +319,17 @@ const ThemeManager = ({ showAlert, role }: ThemeManagerProps) => {
const result = await response.json();
if (result.success) {
setGlobalThemeConfig(result.data);
// 更新运行时配置,确保同步
const runtimeConfig = (window as any).RUNTIME_CONFIG;
if (runtimeConfig) {
runtimeConfig.THEME_CONFIG = result.data;
console.log('已更新运行时主题配置:', result.data);
}
showAlert({
type: 'success',
title: '全局主题配置已保存',
title: '全主题配置已保存',
message: '所有用户将使用新的主题配置',
timer: 3000
});