aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/providers/prism-theme-provider/prism-theme-provider.tsx
blob: 0f0a4a1c691980bad2aedbacfc3cf7ff11563b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import {
  type Dispatch,
  type FC,
  type ReactNode,
  type SetStateAction,
  createContext,
  useEffect,
  useMemo,
} from 'react';
import type { Theme } from '../../../types';
import {
  getDataAttributeFrom,
  getThemeFromSystem,
  themeValidator,
} from '../../helpers';
import { useLocalStorage, useSystemColorScheme } from '../../hooks';

export type PrismThemeContextProps = {
  attribute: string;
  resolvedTheme: Exclude<Theme, 'system'>;
  setTheme: Dispatch<SetStateAction<Theme>>;
  theme: Theme;
};

export const PrismThemeContext = createContext<PrismThemeContextProps>({
  attribute: 'data-prism-theme',
  resolvedTheme: getThemeFromSystem(),
  setTheme: (value) => value,
  theme: 'system',
});

export type PrismThemeProviderProps = {
  /**
   * The attribute name to append to document root.
   */
  attribute: string;
  /**
   * The provider children.
   */
  children?: ReactNode;
  /**
   * The default theme.
   *
   * @default 'system'
   */
  defaultTheme?: Theme;
  /**
   * The key to use in local storage.
   */
  storageKey: string;
};

export const PrismThemeProvider: FC<PrismThemeProviderProps> = ({
  attribute,
  children,
  defaultTheme = 'system',
  storageKey,
}) => {
  const [theme, setTheme] = useLocalStorage(
    storageKey,
    defaultTheme,
    themeValidator
  );
  const resolvedTheme = useSystemColorScheme();
  const dataAttribute = getDataAttributeFrom(attribute);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      document.documentElement.setAttribute(dataAttribute, `${theme}`);
    }

    return () => {
      document.documentElement.removeAttribute(dataAttribute);
    };
  }, [dataAttribute, theme]);

  const value = useMemo(() => {
    return { attribute: dataAttribute, resolvedTheme, setTheme, theme };
  }, [dataAttribute, resolvedTheme, setTheme, theme]);

  return (
    <PrismThemeContext.Provider value={value}>
      {children}
    </PrismThemeContext.Provider>
  );
};