2020-01-17 02:50:57 -07:00
|
|
|
// Insert this script in your index.html right after the <body> tag.
|
|
|
|
// This will help to prevent a flash if dark mode is the default.
|
|
|
|
|
|
|
|
(function() {
|
2020-10-07 09:41:58 -07:00
|
|
|
// Change these if you use something different in your hook.
|
|
|
|
var storageKey = 'darkMode';
|
|
|
|
var classNameDark = 'dark-mode';
|
|
|
|
var classNameLight = 'light-mode';
|
2020-01-17 02:50:57 -07:00
|
|
|
|
2020-10-07 09:41:58 -07:00
|
|
|
function setClassOnDocumentBody(darkMode) {
|
|
|
|
document.body.classList.add(darkMode ? classNameDark : classNameLight);
|
|
|
|
document.body.classList.remove(darkMode ? classNameLight : classNameDark);
|
|
|
|
}
|
2020-01-17 02:50:57 -07:00
|
|
|
|
2020-10-07 09:41:58 -07:00
|
|
|
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);
|
|
|
|
}
|
2020-01-17 02:50:57 -07:00
|
|
|
|
2020-10-07 09:41:58 -07:00
|
|
|
// Determine the source of truth
|
|
|
|
if (localStorageExists) {
|
|
|
|
// source of truth from localStorage
|
|
|
|
setClassOnDocumentBody(localStorageTheme);
|
|
|
|
} else if (supportsColorSchemeQuery) {
|
|
|
|
// source of truth from system
|
|
|
|
setClassOnDocumentBody(mql.matches);
|
|
|
|
localStorage.setItem(storageKey, mql.matches);
|
|
|
|
} else {
|
|
|
|
// source of truth from document.body
|
|
|
|
var isDarkMode = document.body.classList.contains(classNameDark);
|
|
|
|
localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
|
|
|
|
}
|
2020-01-17 02:50:57 -07:00
|
|
|
})();
|