diff options
author | jeffreytse <jeffreytse.mail@gmail.com> | 2020-12-28 12:04:18 +0800 |
---|---|---|
committer | jeffreytse <jeffreytse.mail@gmail.com> | 2020-12-28 12:04:18 +0800 |
commit | ae318f5d72e78b33836987545a99990ee9bec3b3 (patch) | |
tree | 1cb298a2b6b48df0745618bca5a8fe914155401e | |
parent | 1b2d59fd189ebc552f66fb1d920cb24e0ac26d62 (diff) |
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)
-rw-r--r-- | _includes/extensions/theme-toggle.html | 19 |
1 files 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); } })(); </script> |