Dark theme: prevent white flash on page load

This commit is contained in:
Sibren Vasse 2020-05-14 13:16:51 +02:00
parent 4d87df01a3
commit c6e291f7e8
3 changed files with 44 additions and 15 deletions

View File

@ -104,17 +104,4 @@ $(document).ready(function() {
});
});
}
/** Dark mode controller */
if (store.get('dark-mode') === true) {
document.documentElement.setAttribute('data-theme', 'dark')
}
$('[data-toggle="dark-mode"]').on('click', function () {
if (store.get('dark-mode') === true) {
store.set('dark-mode', false);
return document.documentElement.setAttribute('data-theme', 'light')
}
store.set('dark-mode', true)
document.documentElement.setAttribute('data-theme', 'dark')
})
});
});

40
static/assets/js/theme.js Normal file
View File

@ -0,0 +1,40 @@
let setCookie = function(name, value, days) {
if (!name || !value) return false;
let expires = '';
let secure = '';
if (location.protocol === 'https:') secure = 'Secure; ';
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24*60*60*1000));
expires = 'Expires=' + date.toUTCString() + '; ';
}
document.cookie = name + '=' + value + '; ' +
expires +
secure +
'sameSite=Lax; ' +
'domain=' + window.location.hostname + '; ' +
'path=/';
return true;
}
let getCookie = function(name) {
let match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) return match[2];
}
$(document).ready(function() {
/** Dark mode controller */
if (getCookie('dark-mode') === "true") {
document.documentElement.setAttribute('data-theme', 'dark');
}
$('[data-toggle="dark-mode"]').on('click', function () {
if (getCookie('dark-mode') === "true") {
setCookie('dark-mode', 'false', 30);
return document.documentElement.setAttribute('data-theme', 'light')
}
setCookie('dark-mode', 'true', 30);
document.documentElement.setAttribute('data-theme', 'dark')
})
});

View File

@ -1,7 +1,7 @@
{% from "_formhelpers.html" import render_field, render_field_errors %}
<!doctype html>
<html lang="en" dir="ltr">
<html lang="en" dir="ltr" data-theme="{% if request.cookies.get('dark-mode') == 'true' %}dark{% endif %}">
<head>
<meta charset="UTF-8">
<meta name="viewport"
@ -40,6 +40,8 @@
<script src="/static/assets/js/vendors/circle-progress.min.js"></script>
<script src="/static/assets/js/core.js"></script>
<script src="/static/assets/js/theme.js"></script>
<!-- ClipboardJS -->
<script src="/static/vendor/clipboard.min.js"></script>