File tree Expand file tree Collapse file tree 2 files changed +52
-11
lines changed Expand file tree Collapse file tree 2 files changed +52
-11
lines changed Original file line number Diff line number Diff line change @@ -5,12 +5,31 @@ import { useThemeUI } from './context'
5
5
import { createColorStyles } from './custom-properties'
6
6
7
7
const STORAGE_KEY = 'theme-ui-color-mode'
8
- const HAS_STORAGE = typeof Storage !== 'undefined'
9
8
10
9
const storage = {
11
- get : init =>
12
- ( HAS_STORAGE && window . localStorage . getItem ( STORAGE_KEY ) ) || init ,
13
- set : value => HAS_STORAGE && window . localStorage . setItem ( STORAGE_KEY , value ) ,
10
+ get : init => {
11
+ try {
12
+ return window . localStorage . getItem ( STORAGE_KEY ) || init
13
+ } catch ( e ) {
14
+ console . warn (
15
+ 'localStorage is disabled and color mode might not work as expected.' ,
16
+ 'Please check your Site Settings.' ,
17
+ e
18
+ )
19
+ }
20
+ } ,
21
+
22
+ set : value => {
23
+ try {
24
+ window . localStorage . setItem ( STORAGE_KEY , value )
25
+ } catch ( e ) {
26
+ console . warn (
27
+ 'localStorage is disabled and color mode might not work as expected.' ,
28
+ 'Please check your Site Settings.' ,
29
+ e
30
+ )
31
+ }
32
+ } ,
14
33
}
15
34
16
35
export const getMediaQuery = ( ) => {
Original file line number Diff line number Diff line change @@ -37,9 +37,9 @@ test('renders with color modes', () => {
37
37
modes : {
38
38
dark : {
39
39
text : 'white' ,
40
- }
41
- }
42
- }
40
+ } ,
41
+ } ,
42
+ } ,
43
43
} } >
44
44
< Mode />
45
45
</ ThemeProvider >
@@ -64,8 +64,8 @@ test('renders with initial color mode name', () => {
64
64
colors : {
65
65
modes : {
66
66
dark : { } ,
67
- }
68
- }
67
+ } ,
68
+ } ,
69
69
} } >
70
70
< Mode />
71
71
</ ThemeProvider >
@@ -212,8 +212,8 @@ test('inherits color mode state from parent context', () => {
212
212
colors : {
213
213
modes : {
214
214
dark : { } ,
215
- }
216
- }
215
+ } ,
216
+ } ,
217
217
} } >
218
218
< ThemeProvider
219
219
theme = { {
@@ -518,3 +518,25 @@ test('raw color values are passed to theme-ui context when custom properties are
518
518
)
519
519
expect ( color ) . toBe ( 'tomato' )
520
520
} )
521
+
522
+ test ( 'warns when localStorage is disabled' , ( ) => {
523
+ Object . defineProperty ( window , 'localStorage' , {
524
+ get : jest . fn ( ( ) => {
525
+ throw 'SecurityError: The operation is insecure.'
526
+ } ) ,
527
+ } )
528
+
529
+ let mode
530
+ const Consumer = props => {
531
+ const [ colorMode ] = useColorMode ( )
532
+ mode = colorMode
533
+ return false
534
+ }
535
+
536
+ render (
537
+ < ThemeProvider >
538
+ < Consumer />
539
+ </ ThemeProvider >
540
+ )
541
+ expect ( mode ) . toBe ( 'default' )
542
+ } )
You can’t perform that action at this time.
0 commit comments