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

80 lines
2.2 KiB
HTML
Raw Normal View History

2020-07-09 21:15:38 +02:00
{{ $style := "light-without-switcher" }}
{{ if and (isset site.Params "style") (ne site.Params.style "") }}
{{ $style = site.Params.style | lower }}
{{ end }}
{{ if not (in (slice "light-without-switcher" "dark-without-switcher") $style) }}
{{ if ne "auto-without-switcher" $style }}
2024-01-08 17:45:37 +01:00
<div class="theme-switcher">
{{ partial "font-awesome.html" (dict "iconName" "halfcircle" "custom" false) }}
</div>
{{ end }}
2020-07-09 21:15:38 +02:00
<script>
const STORAGE_KEY = 'user-color-scheme'
const defaultTheme = {{ $style }}
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'
document.documentElement.setAttribute('data-theme', currentTheme)
}
document.addEventListener('DOMContentLoaded', function() {
switchButton = document.querySelector('.theme-switcher')
currentTheme = detectCurrentScheme()
if (currentTheme == 'dark') {
document.documentElement.setAttribute('data-theme', 'dark')
}
if (currentTheme == 'auto') {
autoChangeScheme(autoDefinedScheme);
autoDefinedScheme.addListener(autoChangeScheme);
2020-07-09 21:15:38 +02:00
}
if (switchButton) {
2020-07-09 21:15:38 +02:00
switchButton.addEventListener('click', switchTheme, false)
}
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
}
if (!window.matchMedia) {
2020-07-09 21:15:38 +02:00
return 'light'
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
2020-07-09 21:15:38 +02:00
}
return 'light'
}
2020-07-09 21:15:38 +02:00
function switchTheme(e) {
if (currentTheme == 'dark') {
if (localStorage !== null)
localStorage.setItem(STORAGE_KEY, 'light')
document.documentElement.setAttribute('data-theme', 'light')
currentTheme = 'light'
} else {
if (localStorage !== null)
localStorage.setItem(STORAGE_KEY, 'dark')
document.documentElement.setAttribute('data-theme', 'dark')
currentTheme = 'dark'
2020-07-09 21:15:38 +02:00
}
}
function showContent() {
document.body.style.visibility = 'visible';
document.body.style.opacity = 1;
}
</script>
{{ end }}