@@ -16,32 +16,49 @@ type Options = {
16
16
value ?: string ;
17
17
18
18
/**
19
- * Whether the local storage item should only
20
- * retried at initialisation.
19
+ * Whether the local storage is polled for updated.
21
20
*
22
- * @default false
21
+ * The default polling time every 2 seconds.
22
+ * You can change it by setting a number (in ms).
23
23
*/
24
- once ?: boolean ;
24
+ poll ?: boolean | number ;
25
25
} ;
26
26
27
27
export const localStorage = (
28
28
name : string ,
29
- { key, value, once = false } : Options = { }
29
+ { key, value, poll = false } : Options = { }
30
30
) : Plugin => {
31
- const item = once ?? window . localStorage . getItem ( key ?? name ) ;
31
+ const k = key ?? name ;
32
+ let item = window . localStorage . getItem ( k ) ;
33
+
32
34
return {
35
+ onPluginInit ( _ , { onChange } ) {
36
+ const pollInterval =
37
+ poll === true ? 2000 : typeof poll === "number" && poll > 0 ? poll : 0 ;
38
+ if ( hasSetInterval ( ) && pollInterval > 0 ) {
39
+ setInterval ( ( ) => {
40
+ const newItem = window . localStorage . getItem ( k ) ;
41
+ const hasChanged = item !== newItem ;
42
+ item = newItem ;
43
+ if ( hasChanged ) onChange ( ) ;
44
+ } , pollInterval ) ;
45
+ }
46
+ } ,
33
47
onEval ( { variates, rules } , { setResult } ) {
34
48
if ( typeof window === "undefined" ) return ;
35
49
36
50
const index = rules . findIndex ( ( rule ) =>
37
51
takeStrings ( rule ) . some ( ( r ) => {
38
52
if ( r !== name ) return false ;
39
- const i = once ? item : window . localStorage . getItem ( key ?? name ) ;
40
- return value ? i === value : Boolean ( i ) ;
53
+ return value ? item === value : Boolean ( item ) ;
41
54
} )
42
55
) ;
43
56
44
57
if ( index !== - 1 ) setResult ( variates [ index ] ) ;
45
58
} ,
46
59
} ;
47
60
} ;
61
+
62
+ function hasSetInterval ( ) {
63
+ return typeof window !== "undefined" && window . setInterval ;
64
+ }
0 commit comments