Skip to content

Commit f455c41

Browse files
committed
fix(ui): Theme - set init theme based on media query
1 parent 39c3f79 commit f455c41

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

packages/ui/src/context/theme.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ const CLASSLIST_UPDATE_TIMEOUT = 10;
88

99
type ThemeName = 'light' | 'dark';
1010

11+
const getCurrentTheme = (): ThemeName => {
12+
const { matches } = window.matchMedia('(prefers-color-scheme: dark)');
13+
return matches ? 'dark' : 'light';
14+
};
15+
1116
type ThemeContextProps = {
1217
name: ThemeName;
1318
update: (newTheme: ThemeName) => void;
@@ -20,7 +25,7 @@ const ThemeContext = createContext<ThemeContextProps>({
2025

2126
export const ThemeProvider = ({ children }: { children: ReactNode }) => {
2227
const [cookieValue, setCookieValue] = useCookie('theme');
23-
const [name, setName] = useState<ThemeName>(cookieValue === 'dark' ? 'dark' : 'light');
28+
const [name, setName] = useState<ThemeName>((cookieValue as ThemeName) || getCurrentTheme());
2429

2530
const updateClassList = useCallback(async (newTheme: ThemeName) => {
2631
const htmlElm = document.querySelector('html');
@@ -30,9 +35,11 @@ export const ThemeProvider = ({ children }: { children: ReactNode }) => {
3035
await wait(CLASSLIST_UPDATE_TIMEOUT);
3136

3237
if (newTheme === 'dark') {
33-
htmlElm?.classList.replace('light-theme', 'dark-theme');
38+
htmlElm?.classList.remove('light-theme');
39+
htmlElm?.classList.add('dark-theme');
3440
} else {
35-
htmlElm?.classList.replace('dark-theme', 'light-theme');
41+
htmlElm?.classList.remove('dark-theme');
42+
htmlElm?.classList.add('light-theme');
3643
}
3744

3845
await wait(CLASSLIST_UPDATE_TIMEOUT);

0 commit comments

Comments
 (0)