|
1 | | -import { ToggleButton, ToggleButtonGroup, type PaletteOptions } from "@mui/material"; |
| 1 | +import { getLuminance, lighten, ToggleButton, ToggleButtonGroup, type PaletteOptions } from "@mui/material"; |
| 2 | +import type { ThemeOptions } from "@mui/material/styles"; |
| 3 | +import { DEFAULT_DARK_THEME, DEFAULT_THEME } from "../../constants"; |
2 | 4 | import { useInnerTheme } from "../../hooks/useInnerTheme"; |
| 5 | +import { invertLightness } from "../../utils"; |
3 | 6 | import { FieldGroupContainer } from "../FieldGroupContainer/FieldGroupContainer"; |
4 | 7 | import { SubpaletteEditor } from "../SubpaletteEditor/SubpaletteEditor"; |
5 | 8 |
|
6 | 9 | const COLORS_BOTTOM: Array<keyof PaletteOptions> = ["secondary", "error", "warning", "info", "success"]; |
| 10 | +const defaultDarkBackground = DEFAULT_DARK_THEME.palette.background.default; |
| 11 | +const defaultLightBackground = DEFAULT_THEME.palette.background.default; |
7 | 12 |
|
8 | 13 | export const PaletteEditor = () => { |
9 | 14 | const { theme, mergeThemeOptions } = useInnerTheme(); |
| 15 | + const currentMode = theme.palette.mode; |
| 16 | + const isLight = currentMode === "light"; |
| 17 | + const { default: defaultBg } = theme.palette.background; |
10 | 18 | return ( |
11 | 19 | <> |
12 | 20 | <FieldGroupContainer> |
13 | 21 | <ToggleButtonGroup |
14 | 22 | fullWidth |
15 | | - value={theme.palette.mode} |
| 23 | + value={currentMode} |
16 | 24 | exclusive |
17 | 25 | onChange={(_, value: "light" | "dark" | null) => { |
18 | 26 | if (!value) return; |
19 | | - mergeThemeOptions({ palette: { mode: value } }); |
| 27 | + const newTheme: ThemeOptions = { palette: { mode: value } }; |
| 28 | + const isNotDefaultBg = defaultBg !== (isLight ? defaultLightBackground : defaultDarkBackground); |
| 29 | + const isDarkAndUsingDarkBg = !isLight && getLuminance(defaultBg) < 0.3; |
| 30 | + const isLightAndUsingLightBg = isLight && getLuminance(defaultBg) > 0.3; |
| 31 | + |
| 32 | + // Automatically adjust the background if switching modes |
| 33 | + if (isNotDefaultBg && (isLightAndUsingLightBg || isDarkAndUsingDarkBg)) { |
| 34 | + const newBackground = invertLightness(defaultBg); |
| 35 | + newTheme!.palette!.background = { |
| 36 | + paper: isLight ? newBackground : lighten(newBackground, Math.min(1, 1.3 - getLuminance(newBackground))), |
| 37 | + default: newBackground, |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + mergeThemeOptions(newTheme); |
20 | 42 | }} |
21 | 43 | > |
22 | 44 | <ToggleButton value="light">Light</ToggleButton> |
|
0 commit comments