-
Notifications
You must be signed in to change notification settings - Fork 0
/
noflash.js.txt
52 lines (49 loc) · 1.82 KB
/
noflash.js.txt
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
50
51
52
// Insert this script in your index.html right after the <body> tag.
// This will help to prevent a flash if dark themee is the default.
(function () {
// Change these if you use something different in your hook.
var storageKey = 'colorTheme';
var classNames = ['light-theme', 'dark-theme'];
function setClassOnDocumentBody(colorTheme) {
var theme = 'light-theme';
if (colorTheme === false) {
// eslint-disable-next-line prefer-destructuring
theme = classNames[0];
}
if (colorTheme === true) {
// eslint-disable-next-line prefer-destructuring
theme = classNames[1];
}
if (typeof colorTheme === 'string') {
theme = colorTheme;
}
for (var i = 0; i < classNames.length; i++) {
document.body.classList.remove(classNames[i]);
}
document.body.classList.add(theme);
}
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
setClassOnDocumentBody(localStorageTheme);
} else if (supportsColorSchemeQuery) {
// source of truth from system
setClassOnDocumentBody(mql.matches);
localStorage.setItem(storageKey, JSON.stringify('dark-theme'));
} else {
// source of truth from document.body
var iscolorTheme = document.body.classList.contains('dark-theme');
localStorage.setItem(storageKey, iscolorTheme ? JSON.stringify('dark-theme') : JSON.stringify('light-theme'));
}
}());