|
| 1 | +import debounce from "debounce"; |
| 2 | +import type CCStore from "."; |
| 3 | +import { ccComponentStoreChangeEventTypes } from "./component"; |
| 4 | +import { ccComponentPinStoreChangeEventTypes } from "./componentPin"; |
| 5 | +import { ccConnectionStoreChangeEventTypes } from "./connection"; |
| 6 | +import { ccNodeStoreChangeEventTypes } from "./node"; |
| 7 | +import { ccNodePinStoreChangeEventTypes } from "./nodePin"; |
| 8 | + |
| 9 | +export class CCStoreAutoSaver { |
| 10 | + #store: CCStore; |
| 11 | + |
| 12 | + static localStorageKey = "ccStoreAutoSaverState"; |
| 13 | + |
| 14 | + constructor(store: CCStore) { |
| 15 | + this.#store = store; |
| 16 | + } |
| 17 | + |
| 18 | + watch() { |
| 19 | + const save = debounce(this.save.bind(this), 1000); |
| 20 | + for (const eventType of ccComponentStoreChangeEventTypes) { |
| 21 | + this.#store.components.addListener(eventType, save); |
| 22 | + } |
| 23 | + for (const eventType of ccComponentPinStoreChangeEventTypes) { |
| 24 | + this.#store.componentPins.addListener(eventType, save); |
| 25 | + } |
| 26 | + for (const eventType of ccNodeStoreChangeEventTypes) { |
| 27 | + this.#store.nodes.addListener(eventType, save); |
| 28 | + } |
| 29 | + for (const eventType of ccNodePinStoreChangeEventTypes) { |
| 30 | + this.#store.nodePins.addListener(eventType, save); |
| 31 | + } |
| 32 | + for (const eventType of ccConnectionStoreChangeEventTypes) { |
| 33 | + this.#store.connections.addListener(eventType, save); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + save(): void { |
| 38 | + window.localStorage.setItem( |
| 39 | + CCStoreAutoSaver.localStorageKey, |
| 40 | + this.#store.toJSON(), |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + tryRestore(): boolean { |
| 45 | + const json = window.localStorage.getItem(CCStoreAutoSaver.localStorageKey); |
| 46 | + if (json) { |
| 47 | + this.#store.importJson(json); |
| 48 | + return true; |
| 49 | + } else { |
| 50 | + return false; |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments