Files
kiss-translator/src/hooks/Theme.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-10-15 12:43:24 +08:00
import { useEffect, useMemo, useState } from "react";
2023-07-20 13:45:41 +08:00
import { ThemeProvider, createTheme } from "@mui/material/styles";
2024-04-17 15:35:44 +08:00
import { CssBaseline, GlobalStyles } from "@mui/material";
2023-07-20 13:45:41 +08:00
import { useDarkMode } from "./ColorMode";
import { THEME_DARK, THEME_LIGHT } from "../config";
/**
* mui 主题配置
* @param {*} param0
* @returns
*/
export default function Theme({ children, options = {}, styles = {} }) {
2023-08-30 18:05:37 +08:00
const { darkMode } = useDarkMode();
2025-10-15 12:43:24 +08:00
const [systemMode, setSystemMode] = useState(THEME_LIGHT);
useEffect(() => {
if (typeof window.matchMedia !== "function") {
return;
}
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
setSystemMode(mediaQuery.matches ? THEME_DARK : THEME_LIGHT);
};
handleChange(); // Set initial value
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, []);
2023-07-20 13:45:41 +08:00
const theme = useMemo(() => {
2025-11-05 23:15:40 +08:00
let htmlFontSize = 16;
try {
const s = window.getComputedStyle(document.documentElement).fontSize;
htmlFontSize = parseInt(s.replace("px", ""));
} catch (err) {
//
}
2025-10-15 12:43:24 +08:00
const isDarkMode =
darkMode === "dark" || (darkMode === "auto" && systemMode === THEME_DARK);
2023-07-20 13:45:41 +08:00
return createTheme({
palette: {
2025-10-15 12:43:24 +08:00
mode: isDarkMode ? THEME_DARK : THEME_LIGHT,
2023-07-20 13:45:41 +08:00
},
2023-11-22 10:23:14 +08:00
typography: {
2025-11-05 23:15:40 +08:00
htmlFontSize,
2023-11-22 10:23:14 +08:00
},
2023-07-20 13:45:41 +08:00
...options,
});
2025-10-15 12:43:24 +08:00
}, [darkMode, options, systemMode]);
2023-07-20 13:45:41 +08:00
return (
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
2024-04-17 15:35:44 +08:00
<GlobalStyles styles={styles} />
2023-07-20 13:45:41 +08:00
{children}
</ThemeProvider>
);
}