-
Notifications
You must be signed in to change notification settings - Fork 0
/
noflash.js
49 lines (42 loc) · 1.44 KB
/
noflash.js
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
// adapted from: https://github.com/donavon/use-dark-mode
// eslint-disable-next-line no-unused-expressions
!(function() {
var storageKey = 'theme:color-mode'
function setDarkModeInDom(darkMode) {
document.documentElement.dataset.theme = darkMode ? 'dark' : 'light'
}
function setDarkModeInLocalStorage(darkMode) {
const colorMode = JSON.stringify(darkMode ? 'dark' : 'light')
localStorage.setItem(storageKey, colorMode)
}
function setTheme(theme) {
var isDarkMode = theme === 'dark'
setDarkModeInDom(isDarkMode)
setDarkModeInLocalStorage(isDarkMode)
}
var preferDarkQuery = '(prefers-color-scheme: dark)'
var mql = window.matchMedia(preferDarkQuery)
var supportsColorSchemeQuery = mql.media === preferDarkQuery
var localStorageTheme = null
try {
localStorageTheme = localStorage.getItem(storageKey)
} catch (err) {}
var localStorageExists = localStorageTheme !== null
if (localStorageExists) {
localStorageTheme = JSON.parse(localStorageTheme)
}
// Determine the source of truth
if (localStorageExists) {
// source of truth from localStorage
setDarkModeInDom(localStorageTheme === 'dark')
} else if (supportsColorSchemeQuery) {
// source of truth from system
setDarkModeInDom(mql.matches)
setDarkModeInLocalStorage(mql.matches)
} else {
// source of truth from document.body
var isDarkMode = document.documentElement.dataset.theme === 'dark'
setDarkModeInLocalStorage(isDarkMode)
}
window.__setTheme = setTheme
})()