-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdarkMode.js
87 lines (71 loc) · 2.7 KB
/
darkMode.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Remove the no JS class so that the button will show
document.documentElement.classList.remove('no-js');
const STORAGE_KEY = 'user-color-scheme';
const COLOR_MODE_KEY = '--color-mode';
const modeToggleButton = document.querySelector('.js-mode-toggle');
const modeToggleText = document.querySelector('.js-mode-toggle-text');
const modeStatusElement = document.querySelector('.js-mode-status');
/**
* Pass in a custom prop key and this function will return its
* computed value.
* A reduced version of this: https://andy-bell.design/wrote/get-css-custom-property-value-with-javascript/
*/
const getCSSCustomProp = (propKey) => {
let response = getComputedStyle(document.documentElement).getPropertyValue(propKey);
// Tidy up the string if there’s something to work with
if (response.length) {
response = response.replace(/\'|"/g, '').trim();
}
// Return the string response by default
return response;
};
/**
* Takes either a passed settings ('light'|'dark') or grabs that from localStorage.
* If it can’t find the setting in either, it tries to load the CSS color mode,
* controlled by the media query
*/
const applySetting = passedSetting => {
let currentSetting = passedSetting || localStorage.getItem(STORAGE_KEY);
if(currentSetting) {
document.documentElement.setAttribute('data-user-color-scheme', currentSetting);
setButtonLabelAndStatus(currentSetting);
}
else {
setButtonLabelAndStatus(getCSSCustomProp(COLOR_MODE_KEY));
}
}
/**
* Get’s the current setting > reverses it > stores it
*/
const toggleSetting = () => {
let currentSetting = localStorage.getItem(STORAGE_KEY);
switch(currentSetting) {
case null:
currentSetting = getCSSCustomProp(COLOR_MODE_KEY) === 'dark' ? 'light' : 'dark';
break;
case 'light':
currentSetting = 'dark';
break;
case 'dark':
currentSetting = 'light';
break;
}
localStorage.setItem(STORAGE_KEY, currentSetting);
return currentSetting;
}
/**
* A shared method for setting the button text label and visually hidden status element
*/
const setButtonLabelAndStatus = currentSetting => {
modeToggleText.innerText = `${currentSetting === 'dark' ? 'Světlý' : 'Tmavý'} režim`;
modeStatusElement.innerText = `Nyní je zapnutý "${currentSetting} režim"`;
}
/**
* Clicking the button runs the apply setting method which grabs its parameter
* from the toggle setting method.
*/
modeToggleButton.addEventListener('click', evt => {
evt.preventDefault();
applySetting(toggleSetting());
});
applySetting();