merge: dirty-flag auto-save in SharedStoreService (P1a)

This commit is contained in:
CC Worker 2026-05-31 22:22:27 +00:00
commit 135ba4d26d

View File

@ -19,12 +19,17 @@ export class SharedStoreService {
private lastSaveTime: number = Date.now(); private lastSaveTime: number = Date.now();
private autoSaveInterval: ReturnType<typeof setTimeout> | null = null; private autoSaveInterval: ReturnType<typeof setTimeout> | null = null;
private config: AutoSaveConfig; private config: AutoSaveConfig;
private isDirty = false;
private dirtyListener: (() => void) | null = null;
constructor(private store: TLStore, config?: Partial<AutoSaveConfig>) { constructor(private store: TLStore, config?: Partial<AutoSaveConfig>) {
this.config = { this.config = {
...DEFAULT_CONFIG, ...DEFAULT_CONFIG,
...config ...config
}; };
this.dirtyListener = store.listen(() => {
this.isDirty = true;
});
logger.debug('shared-store-service', '🏗️ Initializing SharedStoreService'); logger.debug('shared-store-service', '🏗️ Initializing SharedStoreService');
} }
@ -52,18 +57,16 @@ export class SharedStoreService {
} }
private async checkAndSave(setLoadingState: (state: LoadingState) => void): Promise<void> { private async checkAndSave(setLoadingState: (state: LoadingState) => void): Promise<void> {
const now = Date.now(); if (!this.isDirty) {
if (now - this.lastSaveTime >= this.config.saveInterval) { return;
const currentSnapshot = getSnapshot(this.store); }
const savedSnapshot = storageService.get(StorageKeys.LOCAL_SNAPSHOT);
if (!savedSnapshot || JSON.stringify(currentSnapshot) !== JSON.stringify(savedSnapshot)) { this.isDirty = false;
logger.debug('shared-store-service', '💾 Auto-saving snapshot - changes detected'); const now = Date.now();
await this.saveSnapshot(currentSnapshot, setLoadingState);
this.lastSaveTime = now; if (now - this.lastSaveTime >= this.config.saveInterval) {
} else { await this.saveSnapshot(getSnapshot(this.store), setLoadingState);
logger.trace('shared-store-service', '📝 No changes detected, skipping auto-save'); this.lastSaveTime = now;
}
} }
} }
@ -109,7 +112,10 @@ export class SharedStoreService {
public clear(): void { public clear(): void {
this.stopAutoSave(); this.stopAutoSave();
this.dirtyListener?.();
this.dirtyListener = null;
this.store.clear(); this.store.clear();
this.isDirty = false;
logger.debug('shared-store-service', '🧹 Store cleared'); logger.debug('shared-store-service', '🧹 Store cleared');
} }
} }