diff options
author | jeffreytse <jeffreytse.mail@gmail.com> | 2020-10-03 11:31:43 +0800 |
---|---|---|
committer | jeffreytse <jeffreytse.mail@gmail.com> | 2020-10-03 11:55:14 +0800 |
commit | ba1db7db3e7bf97de56909b1f13592172d550552 (patch) | |
tree | 32b0c1185a71626e54c8a085187d09672547e731 /_includes/extensions/theme-toggle.html | |
parent | a1b848bb55ea525417daf77c1685bedda99abf3a (diff) |
feat: add night mode (#4)
Diffstat (limited to '_includes/extensions/theme-toggle.html')
-rw-r--r-- | _includes/extensions/theme-toggle.html | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/_includes/extensions/theme-toggle.html b/_includes/extensions/theme-toggle.html new file mode 100644 index 0000000..7976e21 --- /dev/null +++ b/_includes/extensions/theme-toggle.html @@ -0,0 +1,90 @@ +<div class="theme-toggle"> + <input type="checkbox" id="theme-switch"> + <label for="theme-switch"> + <div class="toggle"></div> + <div class="names"> + <p class="light">Light</p> + <p class="dark">Dark</p> + </div> + </label> +</div> + +<script> + (function() { + var sw = document.getElementById('theme-switch'); + var html = document.getElementsByTagName('html')[0]; + var themeData = loadThemeData(); + + function saveThemeData(data) { + localStorage.setItem('theme', JSON.stringify(data)); + } + + function loadThemeData() { + var data = localStorage.getItem('theme'); + try { + data = JSON.parse(data ? data : ''); + } catch(e) { + data = { nightShift: null, autoToggleAt: 0 }; + saveThemeData(data); + } + return data; + } + + function handleThemeToggle(nightShift) { + themeData.nightShift = nightShift; + saveThemeData(themeData); + html.dataset.theme = nightShift ? 'dark' : 'light'; + setTimeout(function() { + sw.checked = nightShift ? true : false; + }, 50); + } + + function autoThemeToggle() { + // Next time point of theme toggle + var now = new Date(); + var toggleAt = new Date(); + var hours = now.getHours(); + var nightShift = hours >= 19 || hours <=7; + + if (nightShift) { + if (hours > 7) { + toggleAt.setDate(toggleAt.getDate() + 1); + } + toggleAt.setHours(7); + } else { + toggleAt.setHours(19); + } + + toggleAt.setMinutes(0); + toggleAt.setSeconds(0); + toggleAt.setMilliseconds(0) + + var delay = toggleAt.getTime() - now.getTime(); + + // auto toggle theme mode + setTimeout(function() { + handleThemeToggle(!nightShift); + }, delay); + + return { + nightShift: nightShift, + toggleAt: toggleAt.getTime() + }; + } + + var data = autoThemeToggle(); + + // Listen the theme toggle event + sw.addEventListener('change', function(event) { + handleThemeToggle(event.target.checked); + }); + + // Toggle theme by local setting + if (data.toggleAt > themeData.autoToggleAt) { + themeData.autoToggleAt = data.toggleAt; + handleThemeToggle(data.nightShift); + } else { + handleThemeToggle(themeData.nightShift); + } + })(); +</script> |