1
- import { writable , type Writable } from "svelte/store" ;
1
+ import { writable , type Updater , type Writable } from "svelte/store" ;
2
2
3
3
/**
4
4
* Creates a persistent Svelte store backed by Chrome's sync storage.
@@ -8,48 +8,45 @@ import { writable, type Writable } from "svelte/store";
8
8
* @returns A writable Svelte store
9
9
*/
10
10
export function persistentStore < T > ( key : string , initialValue : T ) : Writable < T > {
11
- const store = writable ( initialValue ) ;
12
- // Ensure each value is updated exactly once in store and in chrome storage
13
- let storeValueQueue : T [ ] = [ ] ;
14
- let chromeValueQueue : T [ ] = [ ] ;
11
+ const store = writable < T > ( initialValue ) ;
15
12
16
- function watchStore ( ) {
17
- store . subscribe ( ( value ) => {
18
- if ( chromeValueQueue . length > 0 && value === chromeValueQueue [ 0 ] ) {
19
- chromeValueQueue . shift ( ) ;
20
- return ;
21
- }
22
-
23
- storeValueQueue . push ( value ) ;
24
- chrome . storage . sync . set ( { [ key ] : value } ) ;
25
- } ) ;
13
+ function updateChromeStorage ( value : T ) : void {
14
+ chrome . storage . sync . set ( { [ key ] : value } ) ;
26
15
}
27
16
28
- function watchChrome ( ) {
17
+ function watchChromeStorage ( ) {
29
18
chrome . storage . sync . onChanged . addListener ( ( changes ) => {
30
- if ( ! Object . hasOwn ( changes , key ) ) return ;
31
-
32
- const value = changes [ key ] . newValue as T ;
33
- if ( storeValueQueue . length > 0 && value === storeValueQueue [ 0 ] ) {
34
- storeValueQueue . shift ( ) ;
35
- return ;
19
+ if ( Object . hasOwn ( changes , key ) ) {
20
+ store . set ( changes [ key ] . newValue ) ;
36
21
}
22
+ } ) ;
23
+ }
37
24
38
- chromeValueQueue . push ( value ) ;
39
- store . set ( value ) ;
25
+ function initStoreFromChromeStorage ( ) {
26
+ chrome . storage . sync . get ( key ) . then ( ( result ) => {
27
+ if ( Object . hasOwn ( result , key ) ) {
28
+ store . set ( result [ key ] ) ;
29
+ }
40
30
} ) ;
41
31
}
42
32
43
- // Initialize the store with the value from Chrome storage
44
- chrome . storage . sync . get ( key ) . then ( ( result ) => {
45
- const value = Object . hasOwn ( result , key ) ? result [ key ] : initialValue ;
46
- chromeValueQueue . push ( value ) ;
47
- store . set ( value ) ;
48
- watchStore ( ) ;
49
- watchChrome ( ) ;
50
- } ) ;
33
+ initStoreFromChromeStorage ( ) ;
34
+ watchChromeStorage ( ) ;
51
35
52
- return store ;
36
+ return {
37
+ set ( this : void , value : T ) : void {
38
+ store . set ( value ) ;
39
+ updateChromeStorage ( value ) ;
40
+ } ,
41
+ update ( this : void , updater : Updater < T > ) : void {
42
+ return store . update ( ( prev : T ) : T => {
43
+ const value = updater ( prev ) ;
44
+ updateChromeStorage ( value ) ;
45
+ return value ;
46
+ } ) ;
47
+ } ,
48
+ subscribe : store . subscribe ,
49
+ } ;
53
50
}
54
51
55
52
export const count = persistentStore ( "count" , 10 ) ;
0 commit comments