Files
plugin-dynamic-theme-style/assets/js/auto-style-switch.js

59 lines
1.7 KiB
JavaScript

/**
* Detects preferred style variant and sets the "style_variant" cookie accordingly.
* Reloads the page if the variant changes.
*/
(function () {
function getCookie(name) {
const match = document.cookie.split('; ').find(r => r.startsWith(name + '='));
return match ? decodeURIComponent(match.split('=')[1]) : '';
}
function setCookie(name, value, maxAgeSeconds) {
document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; max-age=' + maxAgeSeconds;
}
function getUrlParam(name) {
try {
return new URLSearchParams(window.location.search).get(name) || '';
} catch (e) {
return '';
}
}
const urlStyle = getUrlParam('style');
const current = getCookie('style_variant');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const desired = prefersDark ? '01-evening' : 'default';
const MAX_AGE = 31536000; // 1 year
// If URL parameter is present
if (urlStyle) {
if (current !== urlStyle) {
setCookie('style_variant', urlStyle, MAX_AGE);
location.reload();
}
return;
}
// No cookie yet -> set according to preference
if (!current) {
setCookie('style_variant', desired, MAX_AGE);
location.reload();
return;
}
// If cookie already equals desired, nothing to do
if (current === desired) {
return;
}
// Allow automatic switching between default and 01-evening based on preference
if ((current === 'default' || current === '01-evening') && desired !== current) {
setCookie('style_variant', desired, MAX_AGE);
location.reload();
return;
}
// Cookie contains another custom variant -> do not override automatically
})();