From c7425b567e50f338ebe2cdf98c84c08ad0e5f389 Mon Sep 17 00:00:00 2001 From: EGOIST <0x142857@gmail.com> Date: Thu, 9 Dec 2021 21:09:32 +0800 Subject: [PATCH] fix: switch theme when system theme is changed --- src/components/App.tsx | 30 ++++++++++++++++++++++++------ src/components/Navbar.tsx | 5 +---- src/components/Sidebar.tsx | 2 +- src/css/main.css | 10 ++++++++-- tailwind.config.js | 3 +++ 5 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/components/App.tsx b/src/components/App.tsx index 3289124..5250bd8 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -1,4 +1,4 @@ -import { h, FC, useEffect, useState } from 'renderer' +import { h, FC, useEffect, useState, useCallback } from 'renderer' import inView from 'element-in-view' import { InstanceOptions } from '../docup' import { Navbar } from './Navbar' @@ -103,16 +103,34 @@ export const App: FC<{ options: InstanceOptions }> = ({ options }) => { }, []) useEffect(() => { - if (options.useSystemTheme !== false) { - if (window.matchMedia('(prefers-color-scheme: dark)').matches) { - document.documentElement.classList.add('dark') - } - } // Update location.hash on scrolling window.addEventListener('scroll', handleScroll) return () => window.removeEventListener('scroll', handleScroll) }, []) + const mediaQuery = '(prefers-color-scheme: dark)' + const updateDarkModeClass = useCallback(() => { + if (options.useSystemTheme === false) return + + if (window.matchMedia(mediaQuery).matches) { + document.documentElement.classList.add('dark') + } else { + document.documentElement.classList.remove('dark') + } + }, [options.useSystemTheme]) + + useEffect(() => { + updateDarkModeClass() + + const listener = () => updateDarkModeClass() + const m = window.matchMedia(mediaQuery) + m.addEventListener('change', listener) + + return () => { + m.removeEventListener('change', listener) + } + }, []) + return (
{showSidebar && ( diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 9d1c6b9..c01c356 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -8,10 +8,7 @@ export const Navbar: FC<{ toggleSidebar: () => void }> = ({ title, base, navLinks, toggleSidebar }) => { return ( -