1 import { PropsWithChildren, useEffect, useState } from "react"
2 import { ThemeContext, ThemeOption, ThemeValue } from "./theme-context"
3
4 const THEME_KEY = "medusa_admin_theme"
5
6 function getDefaultValue(): ThemeOption {
7 const persisted = localStorage?.getItem(THEME_KEY) as ThemeOption
8
9 if (persisted) {
10 return persisted
11 }
12
13 return "system"
14 }
15
16 function getThemeValue(selected: ThemeOption): ThemeValue {
17 if (selected === "system") {
18 if (window !== undefined) {
19 return window.matchMedia("(prefers-color-scheme: dark)").matches
20 ? "dark"
21 : "light"
22 }
23
24 // Default to light theme if we can't detect the system preference
25 return "light"
26 }
27
28 return selected
29 }
30
31 export const ThemeProvider = ({ children }: PropsWithChildren) => {
32 const [state, setState] = useState<ThemeOption>(getDefaultValue())
33 const [value, setValue] = useState<ThemeValue>(getThemeValue(state))
34
35 const setTheme = (theme: ThemeOption) => {
36 localStorage.setItem(THEME_KEY, theme)
37
38 const themeValue = getThemeValue(theme)
39
40 setState(theme)
41 setValue(themeValue)
42 }
43
44 useEffect(() => {
45 const html = document.querySelector("html")
46 if (html) {
47 /**
48 * Temporarily disable transitions to prevent
49 * the theme change from flashing.
50 */
51 const css = document.createElement("style")
52 css.appendChild(
53 document.createTextNode(
54 `* {
55 -webkit-transition: none !important;
56 -moz-transition: none !important;
57 -o-transition: none !important;
58 -ms-transition: none !important;
59 transition: none !important;
60 }`
61 )
62 )
63 document.head.appendChild(css)
64
65 html.classList.remove(value === "light" ? "dark" : "light")
66 html.classList.add(value)
67 // Ensures that native elements respect the theme, e.g. the scrollbar.
68 html.style.colorScheme = value
69
70 /**
71 * Re-enable transitions after the theme has been set,
72 * and force the browser to repaint.
73 */
74 window.getComputedStyle(css).opacity
75 document.head.removeChild(css)
76 }
77 }, [value])
78
79 return (
80 <ThemeContext.Provider value={{ theme: state, setTheme }}>
81 {children}
82 </ThemeContext.Provider>
83 )
84 }