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

39 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

const icon_light = '{{ index .Site.Params.switch 1 }}'
const icon_dark = '{{ index .Site.Params.switch 0 }}'
2021-11-12 08:47:28 +01:00
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 ? icon_light : icon_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
2021-11-12 08:47:28 +01:00
// 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 ? icon_light : icon_dark;
2021-11-12 08:47:28 +01:00
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')
}