Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addon-themes: Fix switcher initialization after first start #26353

Merged
merged 2 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion code/addons/themes/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export const PARAM_KEY = 'themes' as const;
export const ADDON_ID = `storybook/${PARAM_KEY}}` as const;
export const ADDON_ID = `storybook/${PARAM_KEY}` as const;
export const GLOBAL_KEY = 'theme' as const;
export const THEME_SWITCHER_ID = `${ADDON_ID}/theme-switcher` as const;

Expand Down
21 changes: 17 additions & 4 deletions code/addons/themes/src/theme-switcher.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import React, { Fragment, useMemo } from 'react';
import { useAddonState, useChannel, useGlobals, useParameter } from '@storybook/manager-api';
import {
useAddonState,
useChannel,
useGlobals,
useParameter,
addons,
} from '@storybook/manager-api';
import { styled } from '@storybook/theming';
import { IconButton, WithTooltip, TooltipLinkList } from '@storybook/components';

Expand All @@ -20,16 +26,23 @@ const IconButtonLabel = styled.div(({ theme }) => ({
const hasMultipleThemes = (themesList: ThemeAddonState['themesList']) => themesList.length > 1;
const hasTwoThemes = (themesList: ThemeAddonState['themesList']) => themesList.length === 2;

export const ThemeSwitcher = () => {
export const ThemeSwitcher = React.memo(function ThemeSwitcher() {
const { themeOverride } = useParameter<ThemeParameters>(
PARAM_KEY,
DEFAULT_THEME_PARAMETERS
) as ThemeParameters;
const [{ theme: selected }, updateGlobals] = useGlobals();

const channel = addons.getChannel();
const fromLast = channel.last(THEMING_EVENTS.REGISTER_THEMES);
const initializeThemeState = Object.assign({}, DEFAULT_ADDON_STATE, {
themesList: fromLast?.[0]?.themes || [],
themeDefault: fromLast?.[0]?.defaultTheme || '',
});

const [{ themesList, themeDefault }, updateState] = useAddonState<ThemeAddonState>(
THEME_SWITCHER_ID,
DEFAULT_ADDON_STATE
initializeThemeState
);

useChannel({
Expand Down Expand Up @@ -103,4 +116,4 @@ export const ThemeSwitcher = () => {
}

return null;
};
});
Loading