Skip to content

Instantly share code, notes, and snippets.

@TheRolfFR
Last active December 13, 2022 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheRolfFR/af061cc4695147a21eb0d48eb2f60750 to your computer and use it in GitHub Desktop.
Save TheRolfFR/af061cc4695147a21eb0d48eb2f60750 to your computer and use it in GitHub Desktop.
Dark theme color scheme store with watch
/**
* Dark theme color scheme store with watch
* full demo at https://codepen.io/TheRolf/pen/xxzNreP
* @author TheRolf
*/
window.DarkThemeStore = {
VALUES: {
AUTO: 'auto',
DARK: 'dark',
LIGHT: 'light'
},
DEFAULT: 'auto', // change as will with favorite default value,
STORAGE_KEY: 'THEME',
STORAGE: 'localStorage', // localStorage or sessionStorage
listener: undefined,
getValue: function() {
let foundValue = window[this.STORAGE].getItem(this.STORAGE_KEY);
return foundValue === null ? this.DEFAULT : foundValue;
},
setValue: function(value) {
let result = Object.values(this.VALUES).includes(value);
if(result) {
try {
const oldValue = this.getValue();
window[this.STORAGE].setItem(this.STORAGE_KEY, value);
if(this.listener !== undefined) this.listener(this.isDark(), value, oldValue);
result = true;
} catch(e) {
// possible no storage exception
console.error(e);
result = false;
}
}
return result;
},
isDark: function() {
const value = this.getValue();
return value !== this.VALUES.LIGHT && (value === this.VALUES.DARK || window.matchMedia("(prefers-color-scheme: dark)").matches)
},
setListener: function(fun) {
if(typeof(fun) !== 'function') return false;
this.listener = fun;
return true;
},
watch: function() {
window.matchMedia("(prefers-color-scheme: dark)").onchange = (ev) => {
if(ev.matches && this.listener !== undefined) this.listener(this.isDark(), this.getValue(), this.getValue());
};
window.matchMedia("(prefers-color-scheme: light)").onchange = (ev) => {
if(ev.matches && this.listener !== undefined) this.listener(this.isDark(), this.getValue(), this.getValue());
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment