| import { createSlice } from "@reduxjs/toolkit"; |
| |
| interface SettingState { |
| theme: string; |
| fontSize: string; |
| showSearch: boolean; |
| } |
| |
| const initialState: SettingState = { |
| theme: localStorage.getItem("theme") || "light", |
| fontSize: localStorage.getItem("font") || "medium", |
| showSearch: false, |
| }; |
| |
| const fontSizeMap: Record<string, string> = { |
| small: "12px", |
| medium: "16px", |
| large: "20px", |
| }; |
| document.body.className = initialState.theme; // 设置初始主题 |
| document.documentElement.style.fontSize = fontSizeMap[initialState.fontSize]; |
| export const settingSlice = createSlice({ |
| name:"setting", |
| initialState, |
| reducers:{ |
| toggleSearch: (state) => { |
| state.showSearch = !state.showSearch; |
| }, |
| toggleFontSize: (state) => { |
| state.fontSize = |
| state.fontSize === "small" |
| ? "medium" |
| : state.fontSize === "medium" |
| ? "large" |
| : "small"; |
| document.documentElement.style.fontSize = fontSizeMap[state.fontSize]; // 切换字体大小 |
| localStorage.setItem("font", state.fontSize); // 保存到 localStorage |
| }, |
| toggleTheme: (state) => { |
| const nextTheme = state.theme === "light" ? "dark" : "light"; |
| state.theme = nextTheme; |
| document.body.className = nextTheme; // 切换 body 类名用于全局主题 |
| localStorage.setItem("theme", nextTheme); // 保存到 localStorage |
| console.log("theme:", nextTheme) |
| }, |
| }, |
| }) |
| |
| export default settingSlice.reducer; |
| export const { toggleSearch, toggleFontSize, toggleTheme } = settingSlice.actions; |