hugo-theme-anubis2/layouts/partials/theme-switcher.html

87 lines
3.0 KiB
HTML
Raw Normal View History

{{ $colorTheme := "light" }}
{{ $colorThemeSwitcher := false }}
2020-07-09 21:15:38 +02:00
{{ if and (isset site.Params "colortheme") (ne site.Params.colortheme "") }}
{{ $colorTheme = site.Params.colortheme | lower }}
2024-03-13 09:14:18 +01:00
{{ 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 }}
2020-07-09 21:15:38 +02:00
<script>
const STORAGE_KEY = 'user-color-scheme'
2024-03-18 09:58:43 +01:00
const defaultTheme = "{{ $colorTheme }}"
2020-07-09 21:15:38 +02:00
let currentTheme
let switchButton
let autoDefinedScheme = window.matchMedia('(prefers-color-scheme: dark)')
2020-07-09 21:15:38 +02:00
const autoChangeScheme = e => {
currentTheme = e.matches ? 'dark' : 'light'
2024-03-18 11:38:18 +01:00
document.documentElement.setAttribute('data-theme', currentTheme);
changeGiscusTheme(currentTheme);
2024-03-06 07:22:23 +01:00
}
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)
}
2024-03-18 09:58:43 +01:00
showContent();
})
2020-07-09 21:15:38 +02:00
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';
2024-03-06 07:22:23 +01:00
}
function switchTheme(e) {
currentTheme = (currentTheme === 'dark') ? 'light' : 'dark';
if (localStorage) localStorage.setItem(STORAGE_KEY, currentTheme);
document.documentElement.setAttribute('data-theme', currentTheme);
2024-03-18 11:38:18 +01:00
changeGiscusTheme(currentTheme);
}
2024-03-13 09:14:18 +01:00
function showContent() {
document.body.style.visibility = 'visible';
document.body.style.opacity = 1;
}
2024-03-18 09:58:43 +01:00
2024-03-18 11:38:18 +01:00
function changeGiscusTheme (theme) {
2024-03-18 09:58:43 +01:00
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>
2024-03-13 09:14:18 +01:00
{{ end }}