import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { lightTheme, darkTheme } from '../themes'; // 定义主题类型 export type ThemeType = 'light' | 'dark'; // 定义主题配置类型 export type ThemeConfig = typeof lightTheme; interface ThemeState { themeType: ThemeType; currentTheme: ThemeConfig; } // 从 localStorage 读取保存的主题,默认为 dark const getSavedTheme = (): ThemeType => { try { const saved = localStorage.getItem('app-theme'); return saved === 'light' ? 'light' : 'dark'; } catch { return 'dark'; } }; const initialThemeType = getSavedTheme(); const initialState: ThemeState = { themeType: initialThemeType, currentTheme: initialThemeType === 'light' ? lightTheme : darkTheme, }; const themeSlice = createSlice({ name: 'theme', initialState, reducers: { setTheme: (state, action: PayloadAction) => { const themeType = action.payload; state.themeType = themeType; state.currentTheme = themeType === 'light' ? lightTheme : darkTheme; // 保存到 localStorage try { localStorage.setItem('app-theme', themeType); } catch (error) { console.error('Failed to save theme to localStorage:', error); } }, toggleTheme: (state) => { const newThemeType = state.themeType === 'light' ? 'dark' : 'light'; state.themeType = newThemeType; state.currentTheme = newThemeType === 'light' ? lightTheme : darkTheme; // 保存到 localStorage try { localStorage.setItem('app-theme', newThemeType); } catch (error) { console.error('Failed to save theme to localStorage:', error); } }, }, }); export const { setTheme, toggleTheme } = themeSlice.actions; export default themeSlice.reducer;