-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathstorage-changes.ts
More file actions
72 lines (60 loc) · 1.98 KB
/
Copy pathstorage-changes.ts
File metadata and controls
72 lines (60 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Storage } from 'webextension-polyfill'
export interface StorageChanges {
[key: string]: Storage.StorageChange
}
export type StorageAreaName = 'sync' | 'local' | 'managed'
export type StorageKeyListener = (vals: Storage.StorageChange) => void
export interface Props {
storage: Storage.Static
}
export class StorageChangesManager {
private listeners: Map<StorageAreaName, Map<string, StorageKeyListener>>
private storage: Storage.Static
constructor({ storage }: Props) {
this.resetListeners()
this.storage = storage
this.storage.onChanged.addListener(this.handleChanges)
}
/**
* Set up state for individual storage change listeners.
*/
public resetListeners() {
this.listeners = new Map<
StorageAreaName,
Map<string, StorageKeyListener>
>([
['sync', new Map()],
['local', new Map()],
['managed', new Map()],
])
}
/**
* Master event listener; delegates control to appropriate internal storage key listeners
* based on the changes made.
*/
private handleChanges = (
changes: StorageChanges,
areaName: StorageAreaName,
) => {
const storageAreaHandlers = this.listeners.get(areaName)
// Exit early when no listeners
if (!storageAreaHandlers.size) {
return
}
// For each of the changes, run any listeners for those particular storage keys
for (const [storageKey, values] of Object.entries(changes)) {
const handler = storageAreaHandlers.get(storageKey)
if (handler != null) {
handler(values)
}
}
}
/**
* Affords scheduling of new storage key listeners for specific storage areas.
*/
public addListener = (
areaName: StorageAreaName,
storageKey: string,
listener: StorageKeyListener,
) => this.listeners.get(areaName).set(storageKey, listener)
}