picocss/docs/js/src/theme-switcher.js

96 lines
2.4 KiB
JavaScript
Raw Normal View History

2021-07-09 17:42:10 +07:00
/*
* Theme switcher
*
* Pico.css - https://picocss.com
2023-01-28 13:14:38 +07:00
* Copyright 2019-2023 - Licensed under MIT
2021-07-09 17:42:10 +07:00
*/
export const themeSwitcher = {
2021-07-09 17:42:10 +07:00
// Config
2021-07-09 18:18:39 +07:00
_scheme: 'auto',
change: {
2021-07-09 17:42:10 +07:00
light: '<i>Turn on dark mode</i>',
2021-10-24 12:33:20 +07:00
dark: '<i>Turn off dark mode</i>',
2021-07-09 17:42:10 +07:00
},
2021-07-09 18:18:39 +07:00
buttonsTarget: '.theme-switcher',
localStorageKey: 'picoPreferredColorScheme',
2021-07-09 18:18:39 +07:00
2021-07-09 17:42:10 +07:00
// Init
init() {
this.scheme = this.schemeFromLocalStorage;
2021-07-09 17:42:10 +07:00
this.initSwitchers();
},
// Get color scheme from local storage
get schemeFromLocalStorage() {
if (typeof window.localStorage !== 'undefined') {
if (window.localStorage.getItem(this.localStorageKey) !== null) {
return window.localStorage.getItem(this.localStorageKey);
}
}
return this._scheme;
},
// Preferred color scheme
get preferredColorScheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
2021-07-09 17:42:10 +07:00
},
// Init switchers
initSwitchers() {
2021-07-09 18:18:39 +07:00
const buttons = document.querySelectorAll(this.buttonsTarget);
buttons.forEach(button => {
button.addEventListener('click', () => {
this.scheme == 'dark' ? this.scheme = 'light' : this.scheme = 'dark';
}, false);
});
2021-07-09 17:42:10 +07:00
},
// Add new button
addButton(config) {
let button = document.createElement(config.tag);
button.className = config.class;
document.querySelector(config.target).appendChild(button);
},
// Set scheme
set scheme(scheme) {
if (scheme == 'auto') {
this.preferredColorScheme == 'dark' ? this._scheme = 'dark' : this._scheme = 'light';
2021-07-09 17:42:10 +07:00
}
else if (scheme == 'dark' || scheme == 'light') {
this._scheme = scheme;
}
this.applyScheme();
this.schemeToLocalStorage();
2021-07-09 17:42:10 +07:00
},
2021-07-09 18:18:39 +07:00
// Get scheme
get scheme() {
return this._scheme;
},
2021-07-09 17:42:10 +07:00
// Apply scheme
applyScheme() {
2021-07-09 18:18:39 +07:00
document.querySelector('html').setAttribute('data-theme', this.scheme);
const buttons = document.querySelectorAll(this.buttonsTarget);
2021-10-24 12:33:20 +07:00
buttons.forEach(
button => {
const text = this.scheme == 'dark' ? this.change.dark : this.change.light;
2021-10-24 12:33:20 +07:00
button.innerHTML = text;
button.setAttribute('aria-label', text.replace(/<[^>]*>?/gm, ''));
}
2021-10-24 12:33:20 +07:00
);
},
// Store scheme to local storage
schemeToLocalStorage() {
if (typeof window.localStorage !== 'undefined') {
window.localStorage.setItem(this.localStorageKey, this.scheme);
}
},
2021-10-24 12:33:20 +07:00
};
2021-10-23 12:17:04 +07:00
2021-10-24 12:33:20 +07:00
export default themeSwitcher;