blob: a78aefbb7550953b0e5682d1930488da4d479e51 [file] [log] [blame]
idillon3470d072022-11-22 15:22:34 -05001/*
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 */
18import { PaletteMode } from '@mui/material';
19import { ThemeProvider } from '@mui/material/styles';
20import { createContext, useCallback, useEffect, useMemo, useState } from 'react';
21
22import { buildDefaultTheme } from '../themes/Default';
23import { WithChildren } from '../utils/utils';
24
25interface ICustomThemeContext {
26 mode: PaletteMode;
27 toggleMode: () => void;
28}
29
30export const CustomThemeContext = createContext<ICustomThemeContext>(undefined!);
31
32export 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
45 return (
46 <CustomThemeContext.Provider
47 value={{
48 mode,
49 toggleMode,
50 }}
51 >
52 <ThemeProvider theme={theme}>{children}</ThemeProvider>
53 </CustomThemeContext.Provider>
54 );
55};