Files
mediawiki-theme/resources/scripts/nextbestnetwork/darkmode.js
2025-12-29 18:05:44 +00:00

71 lines
2.4 KiB
JavaScript

/*!
* Color mode toggler for Bootstrap's docs (https://getbootstrap.com/)
*/
$(document).ready(() => {
console.log("DOM fully loaded and parsed");
const getStoredTheme = () => localStorage.getItem('theme');
const setStoredTheme = theme => localStorage.setItem('theme', theme);
const getPreferredTheme = () => {
const storedTheme = getStoredTheme();
console.log("Found stored theme:", storedTheme);
if (storedTheme) {
return storedTheme;
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
const setTheme = theme => {
if (theme === 'auto') {
$('html').attr('data-bs-theme', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
} else {
$('html').attr('data-bs-theme', theme);
}
};
const showActiveTheme = (theme, focus = false) => {
const themeSwitcher = $('#bd-theme');
if (!themeSwitcher.length) {
console.warn("Theme switcher (#bd-theme) not found in DOM.");
return;
}
const themeSwitcherText = $('#bd-theme-text');
const activeThemeIcon = $('.theme-icon-active use');
const btnToActive = $(`[data-bs-theme-value="${theme}"]`);
const svgOfActiveBtn = btnToActive.find('svg use').attr('href');
$('[data-bs-theme-value]').removeClass('active').attr('aria-pressed', 'false');
btnToActive.addClass('active').attr('aria-pressed', 'true');
activeThemeIcon.attr('href', svgOfActiveBtn);
const themeSwitcherLabel = `${themeSwitcherText.text()} (${btnToActive.data('bs-theme-value')})`;
themeSwitcher.attr('aria-label', themeSwitcherLabel);
if (focus) {
themeSwitcher.focus();
}
};
console.log("Setting initial theme...");
setTheme(getPreferredTheme());
showActiveTheme(getPreferredTheme());
$('[data-bs-theme-value]').on('click', function () {
const theme = $(this).data('bs-theme-value');
console.log("Theme changed to:", theme);
setStoredTheme(theme);
setTheme(theme);
showActiveTheme(theme, true);
});
window.matchMedia('(prefers-color-scheme: dark)').on('change', () => {
const storedTheme = getStoredTheme();
if (!storedTheme || storedTheme === 'auto') {
setTheme(getPreferredTheme());
}
});
console.log("Theme toggler initialized!");
});