hugo-theme-anubis2/layouts/partials/theme-switcher.html
2024-04-09 20:03:09 +08:00

90 lines
3.1 KiB
HTML

{{ $colorTheme := "light" }}
{{ $colorThemeSwitcher := false }}
{{ if and (isset site.Params "colortheme") (ne site.Params.colortheme "") }}
{{ $colorTheme = site.Params.colortheme | lower }}
{{ end }}
{{ if and (isset site.Params "colorthemeswitcher") }}
{{ $colorThemeSwitcher = site.Params.colorthemeswitcher }}
{{ end }}
{{ if or (eq $colorThemeSwitcher true) (eq $colorTheme "auto") }}
{{ if site.Params.colorthemeswitcher }}
<div class="theme-switcher">
{{ partial "font-awesome.html" (dict "iconName" "theme-light" "custom" false) }}
</div>
{{ end }}
<script>
const STORAGE_KEY = 'user-color-scheme'
const defaultTheme = "{{ $colorTheme }}"
let currentTheme
let switchButton
let autoDefinedScheme = window.matchMedia('(prefers-color-scheme: dark)')
function switchTheme(e) {
currentTheme = (currentTheme === 'dark') ? 'light' : 'dark';
if (localStorage) localStorage.setItem(STORAGE_KEY, currentTheme);
document.documentElement.setAttribute('data-theme', currentTheme);
changeGiscusTheme(currentTheme);
document.body.dispatchEvent(new CustomEvent(currentTheme + "-theme-set"));
}
const autoChangeScheme = e => {
currentTheme = e.matches ? 'dark' : 'light'
document.documentElement.setAttribute('data-theme', currentTheme);
changeGiscusTheme(currentTheme);
document.body.dispatchEvent(new CustomEvent(currentTheme + "-theme-set"));
}
document.addEventListener('DOMContentLoaded', function () {
switchButton = document.querySelector('.theme-switcher')
currentTheme = detectCurrentScheme()
if (currentTheme === 'auto') {
autoChangeScheme(autoDefinedScheme);
autoDefinedScheme.addListener(autoChangeScheme);
} else {
document.documentElement.setAttribute('data-theme', currentTheme)
}
if (switchButton) {
switchButton.addEventListener('click', switchTheme, false)
}
showContent();
})
function detectCurrentScheme() {
if (localStorage !== null && localStorage.getItem(STORAGE_KEY)) {
return localStorage.getItem(STORAGE_KEY)
}
if (defaultTheme) {
return defaultTheme
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function showContent() {
document.body.style.visibility = 'visible';
document.body.style.opacity = 1;
}
function changeGiscusTheme (theme) {
function sendMessage(message) {
const iframe = document.querySelector('iframe.giscus-frame');
if (!iframe) return;
iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app');
}
sendMessage({
setConfig: {
theme: theme
}
});
}
</script>
{{ end }}