@@ -45,12 +45,62 @@ const createCustomTheme = (theme: DefaultTheme, base: 'light' | 'dark' = 'light'
45
45
46
46
const themeQueryURL = parse ( document . location . search ) . theme ;
47
47
48
+ // Reusable hook to get dark mode state from localStorage
49
+ export const useLocalStorageDarkMode = ( ) => {
50
+ const [ isDark , setIsDark ] = React . useState ( ( ) => {
51
+ if ( themeQueryURL ) return themeQueryURL ;
52
+
53
+ const themeParameters = localStorage . getItem ( 'sb-addon-themes-3' ) ;
54
+ let theme = 'light' ;
55
+ try {
56
+ theme = JSON . parse ( themeParameters || '{}' ) . current ;
57
+ } catch ( error ) {
58
+ console . error ( error ) ;
59
+ }
60
+ return theme === 'dark' ;
61
+ } ) ;
62
+
63
+ React . useEffect ( ( ) => {
64
+ const handleStorageChange = ( ) => {
65
+ const themeParameters = localStorage . getItem ( 'sb-addon-themes-3' ) ;
66
+ let theme = 'light' ;
67
+ try {
68
+ theme = JSON . parse ( themeParameters || '{}' ) . current ;
69
+ } catch ( error ) {
70
+ console . error ( error ) ;
71
+ }
72
+ setIsDark ( theme === 'dark' ) ;
73
+ } ;
74
+
75
+ window . addEventListener ( 'storage' , handleStorageChange ) ;
76
+ return ( ) => window . removeEventListener ( 'storage' , handleStorageChange ) ;
77
+ } , [ ] ) ;
78
+
79
+ return isDark ;
80
+ } ;
81
+
82
+ // Safe hook that tries useDarkMode first, then falls back to localStorage
83
+ export const useSafeDarkMode = ( ) => {
84
+ try {
85
+ return useDarkMode ( ) ;
86
+ } catch ( error ) {
87
+ return useLocalStorageDarkMode ( ) ;
88
+ }
89
+ } ;
90
+
48
91
const Theme = ( { children, isDarkMode, ...props } : BoxProps & { isDarkMode ?: boolean } ) => {
49
92
const [ isDark , setIsDark ] = React . useState ( ( ) => {
50
93
if ( themeQueryURL ) return themeQueryURL ;
51
94
if ( isDarkMode !== undefined ) return isDarkMode ;
52
- // For docs, check localStorage directly
53
- return localStorage . getItem ( 'sb-addon-themes-3' ) === 'dark' ;
95
+
96
+ const themeParameters = localStorage . getItem ( 'sb-addon-themes-3' ) ;
97
+ let theme = 'light' ;
98
+ try {
99
+ theme = JSON . parse ( themeParameters || '{}' ) . current ;
100
+ } catch ( error ) {
101
+ console . error ( error ) ;
102
+ }
103
+ return theme === 'dark' ;
54
104
} ) ;
55
105
56
106
React . useEffect ( ( ) => {
@@ -63,7 +113,13 @@ const Theme = ({ children, isDarkMode, ...props }: BoxProps & { isDarkMode?: boo
63
113
React . useEffect ( ( ) => {
64
114
if ( isDarkMode === undefined ) {
65
115
const handleStorageChange = ( ) => {
66
- const theme = localStorage . getItem ( 'sb-addon-themes-3' ) ;
116
+ const themeParameters = localStorage . getItem ( 'sb-addon-themes-3' ) ;
117
+ let theme = 'light' ;
118
+ try {
119
+ theme = JSON . parse ( themeParameters || '{}' ) . current ;
120
+ } catch ( error ) {
121
+ console . error ( error ) ;
122
+ }
67
123
setIsDark ( theme === 'dark' ) ;
68
124
} ;
69
125
window . addEventListener ( 'storage' , handleStorageChange ) ;
0 commit comments