Generalized to dynamic-theme-style

This commit is contained in:
2025-12-14 19:46:13 +01:00
parent 83f1d8f315
commit 10b7d2b261
7 changed files with 114 additions and 74 deletions

View File

@@ -1,15 +1,59 @@
/**
* Detects system/browser color scheme and sets the "style_variant" cookie accordingly.
* Detects preferred style variant and sets the "style_variant" cookie accordingly.
* Reloads the page if the variant changes.
*/
(function () {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const cookie = document.cookie.split('; ').find(r => r.startsWith('style_variant='));
const current = cookie ? cookie.split('=')[1] : '';
const desired = prefersDark ? '01-evening' : 'default'; // Customize variant names as needed
if (current !== desired) {
document.cookie = "style_variant=" + desired + "; path=/; max-age=31536000";
location.reload();
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
})();