-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoSaver.ts
More file actions
53 lines (47 loc) · 1.5 KB
/
autoSaver.ts
File metadata and controls
53 lines (47 loc) · 1.5 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
import debounce from "debounce";
import type CCStore from ".";
import { ccComponentStoreChangeEventTypes } from "./component";
import { ccComponentPinStoreChangeEventTypes } from "./componentPin";
import { ccConnectionStoreChangeEventTypes } from "./connection";
import { ccNodeStoreChangeEventTypes } from "./node";
import { ccNodePinStoreChangeEventTypes } from "./nodePin";
export class CCStoreAutoSaver {
#store: CCStore;
static localStorageKey = "ccStoreAutoSaverState";
constructor(store: CCStore) {
this.#store = store;
}
watch() {
const save = debounce(this.save.bind(this), 1000);
for (const eventType of ccComponentStoreChangeEventTypes) {
this.#store.components.addListener(eventType, save);
}
for (const eventType of ccComponentPinStoreChangeEventTypes) {
this.#store.componentPins.addListener(eventType, save);
}
for (const eventType of ccNodeStoreChangeEventTypes) {
this.#store.nodes.addListener(eventType, save);
}
for (const eventType of ccNodePinStoreChangeEventTypes) {
this.#store.nodePins.addListener(eventType, save);
}
for (const eventType of ccConnectionStoreChangeEventTypes) {
this.#store.connections.addListener(eventType, save);
}
}
save(): void {
window.localStorage.setItem(
CCStoreAutoSaver.localStorageKey,
this.#store.toJSON(),
);
}
tryRestore(): boolean {
const json = window.localStorage.getItem(CCStoreAutoSaver.localStorageKey);
if (json) {
this.#store.importJson(json);
return true;
} else {
return false;
}
}
}