Skip to content

Commit bf1edaa

Browse files
feat(.storybook): create custom theme decorator
1 parent 1b65874 commit bf1edaa

File tree

3 files changed

+35
-30
lines changed

3 files changed

+35
-30
lines changed

.storybook/ThemeChanger.tsx

Lines changed: 0 additions & 19 deletions
This file was deleted.

.storybook/preview.tsx

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import isChromatic from "chromatic/isChromatic"
22
import { MotionGlobalConfig } from "framer-motion"
3-
import { withThemeByDataAttribute } from "@storybook/addon-themes"
43
import type { Preview } from "@storybook/react"
54

65
import ThemeProvider from "@/components/ThemeProvider"
76

87
import i18n, { baseLocales } from "./i18next"
9-
import { ThemeChanger } from "./ThemeChanger"
8+
import { withNextThemes } from "./withNextThemes"
109

1110
import "@docsearch/css"
1211
import "../src/styles/global.css"
@@ -30,21 +29,18 @@ const preview: Preview = {
3029
locales: baseLocales,
3130
},
3231
decorators: [
33-
withThemeByDataAttribute({
32+
withNextThemes({
3433
themes: {
3534
light: "light",
3635
dark: "dark",
3736
},
3837
defaultTheme: "light",
3938
}),
40-
(Story, context) => {
41-
return (
42-
<ThemeProvider>
43-
<ThemeChanger theme={context.globals.theme} />
44-
<Story />
45-
</ThemeProvider>
46-
)
47-
},
39+
(Story) => (
40+
<ThemeProvider>
41+
<Story />
42+
</ThemeProvider>
43+
),
4844
],
4945
parameters: {
5046
i18n,

.storybook/withNextThemes.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { useEffect } from "react"
2+
import { useTheme } from "next-themes"
3+
import {
4+
type DataAttributeStrategyConfiguration,
5+
DecoratorHelpers,
6+
} from "@storybook/addon-themes"
7+
import type { Decorator } from "@storybook/react/*"
8+
9+
const { initializeThemeState, pluckThemeFromContext } = DecoratorHelpers
10+
11+
export const withNextThemes = ({
12+
themes,
13+
defaultTheme,
14+
}: DataAttributeStrategyConfiguration): Decorator => {
15+
initializeThemeState(Object.keys(themes), defaultTheme)
16+
17+
return (getStory, context) => {
18+
const selectedTheme = pluckThemeFromContext(context)
19+
const selected = selectedTheme || defaultTheme
20+
const { setTheme } = useTheme()
21+
22+
useEffect(() => {
23+
setTheme(selected)
24+
}, [selected, setTheme])
25+
26+
return getStory(context)
27+
}
28+
}

0 commit comments

Comments
 (0)