feat: sync color mode between browser tabs (#6723)

Co-authored-by: Sébastien Lorber <slorber@users.noreply.github.com>
This commit is contained in:
Alexey Pyltsyn 2022-02-23 18:55:57 +03:00 committed by GitHub
parent 26d223dbeb
commit 0c807b3501
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 12 deletions

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import React, {useState, useRef, memo} from 'react';
import React, {useState, useRef, useEffect, memo} from 'react';
import type {Props} from '@theme/Toggle';
import {useThemeConfig, type ColorModeConfig} from '@docusaurus/theme-common';
import useIsBrowser from '@docusaurus/useIsBrowser';
@ -31,6 +31,10 @@ const ToggleComponent = memo(
const [focused, setFocused] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
setChecked(defaultChecked);
}, [defaultChecked]);
return (
<div
className={clsx(styles.toggle, className, {

View file

@ -24,7 +24,8 @@ type ColorModeContextValue = {
readonly setDarkTheme: () => void;
};
const ThemeStorage = createStorageSlot('theme');
const ThemeStorageKey = 'theme';
const ThemeStorage = createStorageSlot(ThemeStorageKey);
const themes = {
light: 'light',
@ -45,7 +46,7 @@ const getInitialTheme = (defaultMode: Themes | undefined): Themes => {
};
const storeTheme = (newTheme: Themes) => {
createStorageSlot('theme').set(coerceToTheme(newTheme));
ThemeStorage.set(coerceToTheme(newTheme));
};
function useColorModeContextValue(): ColorModeContextValue {
@ -69,17 +70,25 @@ function useColorModeContextValue(): ColorModeContextValue {
useEffect(() => {
if (disableSwitch) {
return;
return undefined;
}
try {
const storedTheme = ThemeStorage.get();
if (storedTheme !== null) {
setTheme(coerceToTheme(storedTheme));
const onChange = (e: StorageEvent) => {
if (e.key !== ThemeStorageKey) {
return;
}
} catch (err) {
console.error(err);
}
try {
const storedTheme = ThemeStorage.get();
if (storedTheme !== null) {
setTheme(coerceToTheme(storedTheme));
}
} catch (err) {
console.error(err);
}
};
window.addEventListener('storage', onChange);
return () => {
window.removeEventListener('storage', onChange);
};
}, [disableSwitch, setTheme]);
// PCS is coerced to light mode when printing, which causes the color mode to