@@ -2,6 +2,7 @@ import type { UserPreferences } from '#shared/schemas/userPreferences'
22import { DEFAULT_USER_PREFERENCES } from '#shared/schemas/userPreferences'
33
44const SYNC_DEBOUNCE_MS = 2000
5+ const SYNCED_DISPLAY_MS = 3000
56
67type SyncStatus = 'idle' | 'syncing' | 'synced' | 'error'
78
@@ -15,6 +16,7 @@ let syncStateInstance: PreferencesSyncState | null = null
1516let pendingSavePromise : Promise < boolean > | null = null
1617let hasPendingChanges = false
1718let debounceTimeoutId : ReturnType < typeof setTimeout > | null = null
19+ let syncedResetTimeoutId : ReturnType < typeof setTimeout > | null = null
1820
1921function getSyncState ( ) : PreferencesSyncState {
2022 if ( ! syncStateInstance ) {
@@ -38,6 +40,23 @@ async function fetchServerPreferences(): Promise<UserPreferences | null> {
3840 }
3941}
4042
43+ /** Show 'synced' status briefly, then reset to 'idle'. */
44+ function showSyncedStatus ( ) : void {
45+ const state = getSyncState ( )
46+ if ( syncedResetTimeoutId ) {
47+ clearTimeout ( syncedResetTimeoutId )
48+ }
49+ state . status . value = 'synced'
50+ state . lastSyncedAt . value = new Date ( )
51+ syncedResetTimeoutId = setTimeout ( ( ) => {
52+ syncedResetTimeoutId = null
53+
54+ if ( state . status . value === 'synced' ) {
55+ state . status . value = 'idle'
56+ }
57+ } , SYNCED_DISPLAY_MS )
58+ }
59+
4160async function saveToServer ( preferences : UserPreferences ) : Promise < boolean > {
4261 const state = getSyncState ( )
4362 state . status . value = 'syncing'
@@ -48,8 +67,7 @@ async function saveToServer(preferences: UserPreferences): Promise<boolean> {
4867 method : 'PUT' ,
4968 body : preferences ,
5069 } )
51- state . status . value = 'synced'
52- state . lastSyncedAt . value = new Date ( )
70+ showSyncedStatus ( )
5371 hasPendingChanges = false
5472 return true
5573 } catch ( err ) {
@@ -96,8 +114,7 @@ export function useUserPreferencesSync() {
96114 const serverPreferences = await fetchServerPreferences ( )
97115
98116 if ( serverPreferences ) {
99- state . status . value = 'synced'
100- state . lastSyncedAt . value = new Date ( )
117+ showSyncedStatus ( )
101118 return serverPreferences
102119 }
103120
@@ -120,7 +137,7 @@ export function useUserPreferencesSync() {
120137 function setupRouteGuard ( getPreferences : ( ) => UserPreferences ) : void {
121138 router . beforeEach ( async ( _to , _from , next ) => {
122139 if ( hasPendingChanges && isAuthenticated . value ) {
123- await flushPendingSync ( getPreferences ( ) )
140+ void flushPendingSync ( getPreferences ( ) )
124141 }
125142 next ( )
126143 } )
0 commit comments