hugo-theme-minima/assets/js/theme.js

40 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2021-11-12 08:47:28 +01:00
const light = '{{ index .Site.Params.switch 1 }}'
const dark = '{{ index .Site.Params.switch 0 }}'
const comment = '{{ .Site.Params.comment }}'
const LIGHT = 'light', DARK = 'dark'
2021-08-19 06:42:00 +02:00
2021-11-12 08:47:28 +01:00
const themeSwitcher = document.getElementById('theme-switcher')
// set switcher
themeSwitcher.innerHTML = localStorage.theme === LIGHT ? light : dark
2021-08-19 06:42:00 +02:00
themeSwitcher.addEventListener('click', function () {
2021-11-12 08:47:28 +01:00
const currentTheme = localStorage.theme
const newTheme = currentTheme === LIGHT ? DARK : LIGHT
// switch global theme
switchMinimaTheme(currentTheme, newTheme)
// switch utterance theme if necessary
if (comment === 'utterances')
switchUtteranceTheme(`github-${newTheme}`)
});
function switchMinimaTheme(oldTheme, newTheme) {
const { classList } = document.documentElement
const text = newTheme === LIGHT ? light : dark;
classList.remove(oldTheme);
2021-08-19 06:42:00 +02:00
classList.add(newTheme);
localStorage.theme = newTheme;
themeSwitcher.innerHTML = text;
2021-11-12 08:47:28 +01:00
}
const utteranceClassName = '.utterances-frame'
let utterance;
function switchUtteranceTheme(theme) {
if (!utterance) utterance = document.querySelector(utteranceClassName)
utterance.contentWindow.postMessage({type: 'set-theme', theme}, 'https://utteranc.es')
}