diff --git a/jest.config.js b/jest.config.js index 5e7dd45..135d639 100644 --- a/jest.config.js +++ b/jest.config.js @@ -6,7 +6,12 @@ module.exports = { // Coverage collectCoverage: true, - collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/**/*.types.{ts,tsx}', '!src/**/*.test.{ts,tsx}', '!src/gatsby-types.d.ts'], + collectCoverageFrom: [ + 'src/**/*.{ts,tsx}', + '!src/**/*.types.{ts,tsx}', + '!src/**/*.test.{ts,tsx}', + '!src/gatsby-types.d.ts' + ], coverageDirectory: 'reports/coverage', coveragePathIgnorePatterns: ['/node_modules/'], coverageProvider: 'babel', diff --git a/src/components/dark-mode-switch/dark-mode-switch.tsx b/src/components/dark-mode-switch/dark-mode-switch.tsx index 4518a5d..820c3f2 100644 --- a/src/components/dark-mode-switch/dark-mode-switch.tsx +++ b/src/components/dark-mode-switch/dark-mode-switch.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import type { FunctionComponent, ReactElement } from 'react'; import { FiSun, FiMoon } from 'react-icons/fi'; @@ -6,10 +6,38 @@ import { FiSun, FiMoon } from 'react-icons/fi'; const DarkModeSwitch: FunctionComponent = (): ReactElement => { const [darkMode, setDarkMode] = useState(false); + const changeColorScheme = useCallback((darkMode: boolean) => { + if (darkMode === true) { + window.localStorage.setItem('darkModeColorScheme', 'dark'); + document.documentElement.classList.add('dark'); + } else { + window.localStorage.removeItem('darkModeColorScheme'); + document.documentElement.classList.remove('dark'); + } + + setDarkMode(darkMode); + }, []); + const toggleDarkMode = useCallback(() => { - setDarkMode(!darkMode); - document.documentElement.classList.toggle('dark'); - }, [darkMode]); + changeColorScheme(!darkMode); + }, [darkMode, changeColorScheme]); + + useEffect(() => { + const savedDarkModeColorScheme = window.localStorage.getItem('darkModeColorScheme'); + const darkModeColorSchemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); + + changeColorScheme(savedDarkModeColorScheme === 'dark' ? true : darkModeColorSchemeMediaQuery.matches); + + const darkModeColorSchemeChangeHandler = (event: MediaQueryListEvent) => { + changeColorScheme(event.matches); + }; + + darkModeColorSchemeMediaQuery.addEventListener('change', darkModeColorSchemeChangeHandler); + + return () => { + darkModeColorSchemeMediaQuery.removeEventListener('change', darkModeColorSchemeChangeHandler); + }; + }, [changeColorScheme]); return ( <> diff --git a/src/components/layout/__snapshots__/layout.test.tsx.snap b/src/components/layout/__snapshots__/layout.test.tsx.snap index 9b1fe5b..5f12b65 100644 --- a/src/components/layout/__snapshots__/layout.test.tsx.snap +++ b/src/components/layout/__snapshots__/layout.test.tsx.snap @@ -2,7 +2,7 @@ exports[` should render 1`] = `
= ({ children }): ReactElemen const { title, author } = useSiteMetadata(); return ( -
+
{children}