From c6e291f7e875f2023b554209d9a34cb9cd476a10 Mon Sep 17 00:00:00 2001 From: Sibren Vasse Date: Thu, 14 May 2020 13:16:51 +0200 Subject: [PATCH] Dark theme: prevent white flash on page load --- static/assets/js/core.js | 15 +-------------- static/assets/js/theme.js | 40 +++++++++++++++++++++++++++++++++++++++ templates/base.html | 4 +++- 3 files changed, 44 insertions(+), 15 deletions(-) create mode 100644 static/assets/js/theme.js diff --git a/static/assets/js/core.js b/static/assets/js/core.js index 7b02b27d..25de1c94 100755 --- a/static/assets/js/core.js +++ b/static/assets/js/core.js @@ -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') - }) -}); \ No newline at end of file +}); diff --git a/static/assets/js/theme.js b/static/assets/js/theme.js new file mode 100644 index 00000000..721b2556 --- /dev/null +++ b/static/assets/js/theme.js @@ -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') + }) +}); diff --git a/templates/base.html b/templates/base.html index c7539b7b..0f1827c8 100644 --- a/templates/base.html +++ b/templates/base.html @@ -1,7 +1,7 @@ {% from "_formhelpers.html" import render_field, render_field_errors %} - + + +