Improve the dark mode switch

This commit is contained in:
Eduardo 2019-11-13 00:53:36 +01:00
parent cec8c3ffba
commit 0a3e0a0ae4
5 changed files with 25 additions and 8 deletions

View file

@ -25,7 +25,7 @@ for it, and apply those styles to the <header> tag.
{{/contentFor}}
<section class="m-hero with-picture" data-aos="fade">
<div class="m-hero__picture in-post {{#is "post"}}in-post{{/is}}"></div>
<div class="m-hero__picture {{#is "post"}}in-post{{/is}}"></div>
{{else}}
<section class="m-hero no-picture {{#is "post"}}in-post{{/is}}" data-aos="fade">
{{/if}}

View file

@ -8,7 +8,8 @@ import AOS from 'aos'
import Fuse from 'fuse.js'
import {
isRTL,
formatDate
formatDate,
isDarkMode
} from './helpers'
cssVars({})
@ -34,7 +35,7 @@ $(document).ready(() => {
const $searchResults = $('.js-search-results')
const $searchNoResults = $('.js-no-results')
const $toggleDarkMode = $('.js-toggle-darkmode')
const currentTheme = localStorage.getItem('theme')
const currentSavedTheme = localStorage.getItem('theme')
let fuse = null
let submenuIsOpen = false
@ -184,14 +185,18 @@ $(document).ready(() => {
}
})
if (currentTheme) {
$('html').attr('data-theme', currentTheme)
if (currentSavedTheme) {
$('html').attr('data-theme', currentSavedTheme)
if (currentTheme === 'dark') {
if (currentSavedTheme === 'dark') {
$toggleDarkMode.attr('checked', true)
}
}
if (isDarkMode()) {
$toggleDarkMode.attr('checked', true)
}
var headerElement = document.querySelector('.js-header')
if (headerElement) {

View file

@ -7,6 +7,12 @@ export const isMobile = (width = '768px') => {
return window.matchMedia(`(max-width: ${width})`).matches
}
export const isDarkMode = () => {
const darkModeMatcher = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)')
return darkModeMatcher && darkModeMatcher.matches
}
export const formatDate = (date) => {
if (date) {
return new Date(date).toLocaleDateString(

View file

@ -4,7 +4,7 @@
top: 0;
left: 0;
width: 100%;
height: 100vh;
height: 100%;
opacity: 0;
overflow-y: auto;
z-index: 2;

View file

@ -1,17 +1,19 @@
.m-toggle-darkmode {
position: fixed;
right: $mobile-space;
bottom: $mobile-space;
bottom: 45px;
width: 22px;
height: 22px;
border-radius: 50%;
overflow: hidden;
z-index: 2;
@include respond-to('medium') {
position: relative;
right: auto;
bottom: auto;
margin-left: 20px;
z-index: auto;
}
input {
@ -56,3 +58,7 @@
}
}
}
_:-ms-fullscreen, :root .m-toggle-darkmode {
display: none;
}