Skip to content

Commit d02cfc3

Browse files
authored
Merge pull request #13672 from TylerAPfledderer/fix/sb-color-mode-next-themes-sync
[Storybook] fix(.storybook/preview): sync theme from global with storage key
2 parents 272db97 + bf1edaa commit d02cfc3

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

.storybook/preview.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +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"
8+
import { withNextThemes } from "./withNextThemes"
99

1010
import "@docsearch/css"
1111
import "../src/styles/global.css"
@@ -29,7 +29,7 @@ const preview: Preview = {
2929
locales: baseLocales,
3030
},
3131
decorators: [
32-
withThemeByDataAttribute({
32+
withNextThemes({
3333
themes: {
3434
light: "light",
3535
dark: "dark",

.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)