1- import { debounce } from "@yaakapp-internal/lib" ;
1+ import { debounce , eagerDebounceAsync } from "@yaakapp-internal/lib" ;
22import type { AnyModel , ModelPayload } from "@yaakapp-internal/models" ;
33import { watchWorkspaceFiles } from "@yaakapp-internal/sync" ;
44import { syncWorkspace } from "../commands/commands" ;
@@ -25,49 +25,16 @@ export async function sync({ force }: { force?: boolean } = {}) {
2525 } ) ;
2626}
2727
28- const debouncedSync = debounce ( async ( ) => {
29- await sync ( ) ;
30- } , 1000 ) ;
31-
32- let modelSyncTimer : ReturnType < typeof setTimeout > | null = null ;
33- let modelSyncInFlight = false ;
34-
35- function scheduleModelSync ( ) {
36- if ( modelSyncTimer == null ) {
37- // No timer means this is the first model change in a burst, so sync immediately.
38- void syncModelChanges ( ) ;
39- } else {
40- // Keep pushing the trailing sync out until model writes have been quiet for a bit.
41- clearTimeout ( modelSyncTimer ) ;
42- }
43-
44- modelSyncTimer = setTimeout ( async ( ) => {
45- modelSyncTimer = null ;
46- // Catch any final state that was written while the immediate sync was running.
47- await syncModelChanges ( ) ;
48- } , 1000 ) ;
49- }
50-
51- async function syncModelChanges ( ) {
52- if ( modelSyncInFlight ) return ;
53-
54- modelSyncInFlight = true ;
55- try {
56- await sync ( ) ;
57- } catch ( e ) {
58- console . error ( e ) ;
59- } finally {
60- modelSyncInFlight = false ;
61- }
62- }
28+ const syncAfterFileChange = debounce ( sync , 1000 ) ;
29+ const syncAfterModelWrite = eagerDebounceAsync ( sync , 1000 ) ;
6330
6431/**
6532 * Subscribe to model change events. Since we check the workspace ID on sync, we can
6633 * simply add long-lived subscribers for the lifetime of the app.
6734 */
6835function initModelListeners ( ) {
6936 listenToTauriEvent < ModelPayload > ( "model_write" , ( p ) => {
70- if ( isModelRelevant ( p . payload . model ) ) scheduleModelSync ( ) ;
37+ if ( isModelRelevant ( p . payload . model ) ) syncAfterModelWrite ( ) ;
7138 } ) ;
7239}
7340
@@ -82,11 +49,11 @@ function initFileChangeListeners() {
8249 await unsub ?.( ) ; // Unsub to previous
8350 const workspaceMeta = jotaiStore . get ( activeWorkspaceMetaAtom ) ;
8451 if ( workspaceMeta == null || workspaceMeta . settingSyncDir == null ) return ;
85- debouncedSync ( ) ; // Perform an initial sync when switching workspace
52+ syncAfterFileChange ( ) ; // Perform an initial sync when switching workspace
8653 unsub = watchWorkspaceFiles (
8754 workspaceMeta . workspaceId ,
8855 workspaceMeta . settingSyncDir ,
89- debouncedSync ,
56+ syncAfterFileChange ,
9057 ) ;
9158 } ) ;
9259}
0 commit comments