From ae318f5d72e78b33836987545a99990ee9bec3b3 Mon Sep 17 00:00:00 2001 From: jeffreytse Date: Mon, 28 Dec 2020 12:04:18 +0800 Subject: feat: better dark mode strategy (#15) Whatever the user's choice is, it will supersede the default setting of the site and be kept during the visit (session). Only the dark mode setting is `manual`, the user's choise will be always kept on every visit (i.e. no matter the browser is closed or not) --- _includes/extensions/theme-toggle.html | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/_includes/extensions/theme-toggle.html b/_includes/extensions/theme-toggle.html index 623c425..634c932 100644 --- a/_includes/extensions/theme-toggle.html +++ b/_includes/extensions/theme-toggle.html @@ -17,18 +17,22 @@ (function() { var sw = document.getElementById('theme-switch'); var html = document.getElementsByTagName('html')[0]; + var nightModeOption = ('{{ night_mode }}' || 'auto').toLowerCase(); + var storage = nightModeOption === 'manual' + ? localStorage + : sessionStorage; var themeData = loadThemeData(); function saveThemeData(data) { - localStorage.setItem('theme', JSON.stringify(data)); + storage.setItem('theme', JSON.stringify(data)); } function loadThemeData() { - var data = localStorage.getItem('theme'); + var data = storage.getItem('theme'); try { data = JSON.parse(data ? data : ''); } catch(e) { - data = { nightShift: false, autoToggleAt: 0 }; + data = { nightShift: undefined, autoToggleAt: 0 }; saveThemeData(data); } return data; @@ -81,9 +85,6 @@ handleThemeToggle(event.target.checked); }); - var nightModeOption = '{{ night_mode }}' || 'auto'; - nightModeOption = nightModeOption.toLowerCase(); - if (nightModeOption == 'auto') { var data = autoThemeToggle(); @@ -97,7 +98,11 @@ } else if (nightModeOption == 'manual') { handleThemeToggle(themeData.nightShift); } else { - handleThemeToggle(nightModeOption == 'on'); + var nightShift = themeData.nightShift; + if (nightShift === undefined) { + nightShift = nightModeOption === 'on'; + } + handleThemeToggle(nightShift); } })(); -- cgit v1.2.3