2023-10-16 01:36:59 +02:00
|
|
|
/* @preserve Dark mode Init */
|
|
|
|
/*
|
2024-03-27 04:13:48 +01:00
|
|
|
* There are two colour palettes on CSS for the data-theme: 'light' and 'dark'.
|
|
|
|
* Initially the script checks if a theme is set in session storage and
|
2023-10-16 01:36:59 +02:00
|
|
|
* alternatively listens to a MediaQuery callback looking for "prefers-color-scheme: dark".
|
2024-03-27 04:13:48 +01:00
|
|
|
*
|
|
|
|
* The variables darkBtn and lightBtn are defined in head.liquid from the _data/translations.yml
|
|
|
|
* The isAutoTheme is defined in head.liquid from the _config.yml
|
2023-10-16 01:36:59 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
const themeButton = {
|
2024-03-27 04:13:48 +01:00
|
|
|
'light': `<i class="fas fa-adjust" aria-hidden="true"></i><span class="navbar-label-with-icon"> ${darkBtn}</span>`,
|
|
|
|
'dark': `<i class="fas fa-adjust fa-rotate-180" aria-hidden="true"></i><span class="navbar-label-with-icon"> ${lightBtn}</span>`
|
|
|
|
};
|
2023-10-16 01:36:59 +02:00
|
|
|
|
2024-03-27 04:13:48 +01:00
|
|
|
function currentTheme(){
|
|
|
|
return localStorage.getItem('theme');
|
|
|
|
}
|
2023-10-16 01:36:59 +02:00
|
|
|
|
|
|
|
function setMode(theme) {
|
2024-03-27 04:13:48 +01:00
|
|
|
document.documentElement.setAttribute('data-theme', theme);
|
|
|
|
localStorage.setItem('theme', theme);
|
|
|
|
const toggle = document.getElementById('theme-toggle');
|
2023-10-16 01:36:59 +02:00
|
|
|
if (toggle) {
|
2024-03-27 04:13:48 +01:00
|
|
|
toggle.innerHTML = themeButton[theme];
|
2023-10-16 01:36:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function themeToggle() {
|
2024-03-27 04:13:48 +01:00
|
|
|
let sessionPrefers = currentTheme();
|
2023-10-16 01:36:59 +02:00
|
|
|
if (sessionPrefers === 'light') {
|
2024-03-27 04:13:48 +01:00
|
|
|
setMode('dark');
|
2023-10-16 01:36:59 +02:00
|
|
|
} else {
|
2024-03-27 04:13:48 +01:00
|
|
|
setMode('light');
|
2023-10-16 01:36:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-27 04:13:48 +01:00
|
|
|
function bootstrapTheme() {
|
2023-10-16 01:36:59 +02:00
|
|
|
if (isAutoTheme) {
|
|
|
|
if (!currentTheme()) {
|
|
|
|
// Load browser's preference
|
|
|
|
let browserPrefersDark = window.matchMedia('(prefers-color-scheme: dark)');
|
2024-03-27 04:13:48 +01:00
|
|
|
if (browserPrefersDark.matches) localStorage.setItem('theme', 'dark');
|
2023-10-16 01:36:59 +02:00
|
|
|
browserPrefersDark.addEventListener('change', () => {
|
2024-03-27 04:13:48 +01:00
|
|
|
if (browserPrefersDark.matches) localStorage.setItem('theme', 'dark');
|
2023-10-16 01:36:59 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
// Load theme
|
2024-03-27 04:13:48 +01:00
|
|
|
let sessionPrefers = currentTheme();
|
|
|
|
setMode(sessionPrefers ? sessionPrefers : 'light');
|
2023-10-16 01:36:59 +02:00
|
|
|
}
|
|
|
|
}
|
2024-03-27 04:13:48 +01:00
|
|
|
|
|
|
|
// Init
|
|
|
|
(function () {
|
|
|
|
bootstrapTheme();
|
|
|
|
})()
|