https://blog.naskya.net/
[[ 🗃
^wzWnj blog
]] ::
[📥 Inbox]
[📤 Outbox]
[💥 Errbox]
[🐤 Followers]
[🤝 Collaborators]
[🏗 Projects]
[🛠 Commits]
Clone
HTTPS:
git clone https://code.naskya.net/repos/wzWnj
SSH:
git clone USERNAME@code.naskya.net:wzWnj
Branches
Tags
colorScheme.ts
// This file is copy from https://github.com/CaiJimmy/hugo-theme-stack/blob/dda55f87e28e5132abfe0bcb4991e93c79688e5e/assets/ts/colorScheme.ts
// All right reserved by Jimmy Cai
type colorScheme = 'light' | 'dark' | 'auto';
class ThemeColorScheme {
private localStorageKey = 'ThemeColorScheme';
private currentScheme: colorScheme;
private systemPreferScheme: colorScheme;
constructor(toggleEl: HTMLElement) {
this.bindMatchMedia();
this.currentScheme = this.getSavedScheme();
this.dispatchEvent(document.documentElement.dataset.userColorScheme as colorScheme);
if (toggleEl)
this.bindClick(toggleEl);
if (document.body.style.transition == '')
document.body.style.setProperty('transition', 'background-color .3s ease');
}
private saveScheme() {
localStorage.setItem(this.localStorageKey, this.currentScheme);
}
private bindClick(toggleEl: HTMLElement) {
toggleEl.addEventListener('click', (e) => {
if (this.isDark()) {
/// Disable dark mode
this.currentScheme = 'light';
}
else {
this.currentScheme = 'dark';
}
this.setBodyClass();
if (this.currentScheme == this.systemPreferScheme) {
/// Set to auto
this.currentScheme = 'auto';
}
this.saveScheme();
})
}
private isDark() {
return (this.currentScheme == 'dark' || this.currentScheme == 'auto' && this.systemPreferScheme == 'dark');
}
private dispatchEvent(colorScheme: colorScheme) {
const event = new CustomEvent('onColorSchemeChange', {
detail: colorScheme
});
window.dispatchEvent(event);
}
private setBodyClass() {
if (this.isDark()) {
document.documentElement.dataset.userColorScheme = 'dark';
}
else {
document.documentElement.dataset.userColorScheme = 'light';
}
this.dispatchEvent(document.documentElement.dataset.userColorScheme as colorScheme);
}
private getSavedScheme(): colorScheme {
const savedScheme = localStorage.getItem(this.localStorageKey);
if (savedScheme == 'light' || savedScheme == 'dark' || savedScheme == 'auto') return savedScheme;
else return 'auto';
}
private bindMatchMedia() {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (e.matches) {
this.systemPreferScheme = 'dark';
}
else {
this.systemPreferScheme = 'light';
}
this.setBodyClass();
});
}
}
export default ThemeColorScheme;