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

76 lines
2 KiB
JavaScript
Raw Normal View History

2023-05-12 14:30:35 +02:00
import * as params from '@params';
const comment = params.comment.provider
const default_theme_config = params.defaulttheme
const icon_light = params.switch[1]
const icon_dark = params.switch[0]
2023-04-10 15:37:53 +02:00
const THEME_LIGHT = default_theme_config === 'system' ? 'light' : default_theme_config
2022-11-09 09:03:19 +01:00
const THEME_DARK = 'dark'
/** @type {HTMLElement} */
let toggler
/** @type {HTMLIFrameElement} */
let utterances
/** @type {HTMLIFrameElement} */
let giscus
/** @param {string} id */
export function setup_theme_switch(id) {
2023-04-10 15:37:53 +02:00
if (!toggler) {
toggler = document.getElementById(id)
}
toggler.innerHTML = localStorage.theme === THEME_LIGHT ? icon_light : icon_dark
toggler.addEventListener('click', switch_theme);
2022-11-09 09:03:19 +01:00
}
function switch_theme() {
2023-04-10 15:37:53 +02:00
const current = localStorage.getItem('theme')
const next = current === THEME_LIGHT ? THEME_DARK : THEME_LIGHT
2022-11-09 09:03:19 +01:00
2023-04-10 15:37:53 +02:00
switch_minima_theme(current, next)
2022-11-09 09:03:19 +01:00
2023-04-10 15:37:53 +02:00
switch (comment) {
case 'utterances':
switch_utterances_theme(`github-${next}`)
break
2022-11-09 09:03:19 +01:00
case 'giscus':
2023-04-10 15:37:53 +02:00
switch_giscus_theme(next)
break
2022-11-09 09:03:19 +01:00
default:
2023-04-10 15:37:53 +02:00
}
2021-11-12 08:47:28 +01:00
}
2022-11-09 09:03:19 +01:00
/**
* @param {string} current
* @param {string} next
*/
function switch_minima_theme(current, next) {
2023-04-10 15:37:53 +02:00
const { classList } = document.documentElement
const icon = next === THEME_LIGHT ? icon_light : icon_dark;
2021-11-12 08:47:28 +01:00
2023-04-10 15:37:53 +02:00
classList.remove(current);
classList.add(next);
localStorage.setItem('theme', next);
toggler.innerHTML = icon;
2022-11-09 09:03:19 +01:00
}
/** @param {string} theme */
function switch_utterances_theme(theme) {
2023-04-10 15:37:53 +02:00
if (theme !== 'dark') {
theme = 'light'
}
utterances = utterances || document.querySelector('iframe.utterances-frame')
if (!utterances) return
utterances.contentWindow.postMessage({ type: 'set-theme', theme }, 'https://utteranc.es')
2022-11-09 09:03:19 +01:00
}
/** @param {string} theme */
function switch_giscus_theme(theme) {
2023-04-10 15:37:53 +02:00
if (theme !== 'dark') {
theme = 'light_protanopia'
}
giscus = giscus || document.querySelector('iframe.giscus-frame')
if (!giscus) return
giscus.contentWindow.postMessage({ giscus: { setConfig: { theme } } }, 'https://giscus.app')
2022-11-09 09:03:19 +01:00
}