|
| 1 | +import { DecoratorHelpers } from '@storybook/addon-themes'; |
| 2 | +import type { ReactRenderer } from '@storybook/react'; |
| 3 | +import { ThemeProvider, type ThemeProviderProps, useTheme } from 'next-themes'; |
| 4 | +import { type PropsWithChildren, useEffect } from 'react'; |
| 5 | +import type { DecoratorFunction } from 'storybook/internal/types'; |
| 6 | + |
| 7 | +type ThemeSwitcherProps = PropsWithChildren<{ |
| 8 | + theme: string; |
| 9 | +}>; |
| 10 | + |
| 11 | +const ThemeSwitcher = ({ theme, children }: ThemeSwitcherProps) => { |
| 12 | + const { setTheme } = useTheme(); |
| 13 | + useEffect(() => setTheme(theme), [theme]); |
| 14 | + /** |
| 15 | + * If you're using tailwind and want your background to be displayed in the preview, |
| 16 | + * use <div className="bg-background">{children}</div> instead |
| 17 | + */ |
| 18 | + return children; |
| 19 | +}; |
| 20 | + |
| 21 | +type NextThemesDecorator = Omit<ThemeProviderProps, 'defaultTheme' | 'themes'> & { |
| 22 | + themes: Record<string, string>; |
| 23 | + defaultTheme: string; |
| 24 | +}; |
| 25 | + |
| 26 | +const { initializeThemeState, pluckThemeFromContext } = DecoratorHelpers; |
| 27 | + |
| 28 | +export const withNextThemes = ({ |
| 29 | + themes, |
| 30 | + defaultTheme, |
| 31 | + ...props |
| 32 | +}: NextThemesDecorator): DecoratorFunction<ReactRenderer> => { |
| 33 | + initializeThemeState(Object.keys(themes), defaultTheme); |
| 34 | + |
| 35 | + return (Story, context) => { |
| 36 | + const selectedTheme = pluckThemeFromContext(context); |
| 37 | + const { themeOverride } = context.parameters.themes ?? {}; |
| 38 | + const selected = themeOverride ?? selectedTheme ?? defaultTheme; |
| 39 | + |
| 40 | + return ( |
| 41 | + <ThemeProvider defaultTheme={defaultTheme} {...props}> |
| 42 | + <ThemeSwitcher theme={selected}> |
| 43 | + <Story /> |
| 44 | + </ThemeSwitcher> |
| 45 | + </ThemeProvider> |
| 46 | + ); |
| 47 | + }; |
| 48 | +}; |
0 commit comments