From bc2cab9ff83ca2e865bbcebd697567733d0cb99a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beltr=C3=A1n=20Rengifo?= Date: Wed, 21 Dec 2022 13:37:12 +0100 Subject: [PATCH] fix: respect current param by using a new property in the store --- src/Tool.tsx | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/Tool.tsx b/src/Tool.tsx index cb356e9f..a3181b12 100644 --- a/src/Tool.tsx +++ b/src/Tool.tsx @@ -33,6 +33,8 @@ interface DarkModeStore { lightClass: string; /** Apply mode to iframe */ stylePreview: boolean; + /** Persist if the user has set the theme */ + userHasExplicitlySetTheTheme: boolean; } const STORAGE_KEY = 'sb-addon-themes-3'; @@ -45,6 +47,7 @@ const defaultParams: Required> = { light: themes.light, lightClass: 'light', stylePreview: false, + userHasExplicitlySetTheTheme: false, }; /** Persist the dark mode settings in localStorage */ @@ -146,7 +149,10 @@ export function DarkMode({ api }: DarkModeProps) { const { current: defaultMode, stylePreview, ...params } = darkModeParams; const channel = api.getChannel(); // Save custom themes on init - const initialMode = React.useMemo(() => store(params).current, [params]); + const userHasExplicitlySetTheTheme = React.useMemo( + () => store(params).userHasExplicitlySetTheTheme, + [params] + ); /** Set the theme in storybook, update the local state, and emit an event */ const setMode = React.useCallback( (mode: Mode) => { @@ -176,6 +182,10 @@ export function DarkMode({ api }: DarkModeProps) { /** Update the theme based on the color preference */ function prefersDarkUpdate(event: MediaQueryListEvent) { + if (userHasExplicitlySetTheTheme || defaultMode) { + return; + } + updateMode(event.matches ? 'dark' : 'light'); } @@ -185,6 +195,13 @@ export function DarkMode({ api }: DarkModeProps) { setMode(current); }, [setMode]); + /** Handle the user event and side effects */ + const handleIconClick = () => { + updateMode(); + const currentStore = store(); + updateStore({ ...currentStore, userHasExplicitlySetTheTheme: true }); + }; + /** When storybook params change update the stored themes */ React.useEffect(() => { const currentStore = store(); @@ -219,7 +236,7 @@ export function DarkMode({ api }: DarkModeProps) { // need the effect to run whenever defaultMode is updated React.useEffect(() => { // If a users has set the mode this is respected - if (initialMode) { + if (userHasExplicitlySetTheTheme) { return; } @@ -228,14 +245,14 @@ export function DarkMode({ api }: DarkModeProps) { } else if (prefersDark.matches) { updateMode('dark'); } - }, [defaultMode, updateMode, initialMode]); + }, [defaultMode, updateMode, userHasExplicitlySetTheTheme]); return ( updateMode()} + onClick={handleIconClick} > {isDark ? : }