idillon | 3470d07 | 2022-11-22 15:22:34 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | import { PaletteMode } from '@mui/material'; |
| 19 | import { ThemeProvider } from '@mui/material/styles'; |
| 20 | import { createContext, useCallback, useEffect, useMemo, useState } from 'react'; |
| 21 | |
| 22 | import { buildDefaultTheme } from '../themes/Default'; |
| 23 | import { WithChildren } from '../utils/utils'; |
| 24 | |
| 25 | interface ICustomThemeContext { |
| 26 | mode: PaletteMode; |
| 27 | toggleMode: () => void; |
| 28 | } |
| 29 | |
| 30 | export const CustomThemeContext = createContext<ICustomThemeContext>(undefined!); |
| 31 | |
| 32 | export default ({ children }: WithChildren) => { |
| 33 | const [mode, setMode] = useState<PaletteMode>('light'); |
| 34 | |
| 35 | useEffect(() => { |
| 36 | const browserIsDark = window.matchMedia('(prefers-color-scheme: dark)').matches; |
| 37 | // TODO: Check if account saved a preference and use it |
| 38 | setMode(browserIsDark ? 'dark' : 'light'); |
| 39 | }, []); |
| 40 | |
| 41 | const toggleMode = useCallback(() => setMode((mode) => (mode === 'light' ? 'dark' : 'light')), [setMode]); |
| 42 | |
| 43 | const theme = useMemo(() => buildDefaultTheme(mode), [mode]); |
| 44 | |
simon | 5c67796 | 2022-12-02 16:51:54 -0500 | [diff] [blame] | 45 | const value = useMemo( |
| 46 | () => ({ |
| 47 | mode, |
| 48 | toggleMode, |
| 49 | }), |
| 50 | [mode, toggleMode] |
| 51 | ); |
| 52 | |
idillon | 3470d07 | 2022-11-22 15:22:34 -0500 | [diff] [blame] | 53 | return ( |
simon | 5c67796 | 2022-12-02 16:51:54 -0500 | [diff] [blame] | 54 | <CustomThemeContext.Provider value={value}> |
idillon | 3470d07 | 2022-11-22 15:22:34 -0500 | [diff] [blame] | 55 | <ThemeProvider theme={theme}>{children}</ThemeProvider> |
| 56 | </CustomThemeContext.Provider> |
| 57 | ); |
| 58 | }; |