fix: Prevent flash of light mode if dark mode is selected (#446)

This commit is contained in:
Sebastian Silbermann 2021-11-22 11:16:49 +00:00 committed by GitHub
parent d2165177ab
commit 630089cdb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 21 deletions

View File

@ -35,6 +35,29 @@
{% endblock pageStyles %}
</head>
<body>
<script>
/**
* @type String
*/
let userThemeSetting = localStorage.getItem('sdUserTheme');
if (userThemeSetting) {
document.documentElement.setAttribute(
'data-user-theme',
userThemeSetting
);
}
window.setUserPreference = function setUserPreference(value) {
localStorage.setItem('sdUserTheme', value);
document.documentElement.setAttribute('data-user-theme', value);
}
window.unsetUserPreference = function unsetUserPreference() {
localStorage.removeItem('sdUserTheme');
document.documentElement.removeAttribute('data-user-theme');
}
</script>
{% block content %}{% endblock content %}
{% include 'components/base/site-footer.njk' %}
{% block pageScript %}

View File

@ -9,17 +9,15 @@ function initThemeSwitch() {
let $buttons = $switchContainer.querySelectorAll('[type="radio"]');
function setInitialState() {
/**
* @type String
*/
let userThemeSetting = localStorage.getItem('sdUserTheme');
function setInitialState() {
if (userThemeSetting) {
document.documentElement.setAttribute(
'data-user-theme',
userThemeSetting
let userThemeSetting = document.documentElement.getAttribute(
'data-user-theme'
);
if (userThemeSetting) {
$switchContainer.querySelector(
`[value="${userThemeSetting}"]`
).checked = true;
@ -28,25 +26,15 @@ function initThemeSwitch() {
}
}
function setUserPreference(value) {
localStorage.setItem('sdUserTheme', value);
document.documentElement.setAttribute('data-user-theme', value);
}
function unsetUserPreference() {
localStorage.removeItem('sdUserTheme');
document.documentElement.removeAttribute('data-user-theme');
}
Array.from($buttons).forEach(function($button) {
$button.addEventListener('change', function() {
// only run the switch functionality for the currently active radio button
if (!$button.checked) return;
if (userOverwrite.includes($button.value)) {
setUserPreference($button.value);
window.setUserPreference($button.value);
} else {
unsetUserPreference();
window.unsetUserPreference();
}
});
});