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 %} {% endblock pageStyles %}
</head> </head>
<body> <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 %} {% block content %}{% endblock content %}
{% include 'components/base/site-footer.njk' %} {% include 'components/base/site-footer.njk' %}
{% block pageScript %} {% block pageScript %}

View File

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