-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcolorScheme.ts
36 lines (31 loc) · 1010 Bytes
/
colorScheme.ts
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
import React from 'react';
function detectColorScheme(): boolean {
var theme = 'light'; //default to light
//local storage is used to override OS theme settings
if (localStorage.getItem('theme')) {
if (localStorage.getItem('theme') == 'dark') {
var theme = 'dark';
}
} else if (!window.matchMedia) {
//matchMedia method not supported
return false;
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
//OS theme setting detected as dark
var theme = 'dark';
}
//dark theme preferred, set document with a `data-theme` attribute
if (theme == 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
}
return theme === 'dark';
}
function switchTheme(dark: boolean) {
if (!dark) {
localStorage.setItem('theme', 'dark');
document.documentElement.setAttribute('data-theme', 'dark');
} else {
localStorage.setItem('theme', 'light');
document.documentElement.setAttribute('data-theme', 'light');
}
}
export { detectColorScheme, switchTheme };