| 48 | * The backend writes the state to `session_state.json` in the active workspace. |
| 49 | */ |
| 50 | export function useAutoSave() { |
| 51 | const state = useSelector((s: DataFormulatorState) => s); |
| 52 | const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 53 | const isSavingRef = useRef(false); |
| 54 | const pendingRef = useRef(false); |
| 55 | const lastErrorNotifyRef = useRef(0); |
| 56 | |
| 57 | useEffect(() => { |
| 58 | // Don't auto-save while a session is loading, no workspace active, or no tables loaded |
| 59 | if (state.sessionLoading || !state.activeWorkspace || state.tables.length === 0) { |
| 60 | return; |
| 61 | } |
| 62 | |
| 63 | // Debounce: reset timer on every state change |
| 64 | if (timerRef.current) { |
| 65 | clearTimeout(timerRef.current); |
| 66 | } |
| 67 | |
| 68 | timerRef.current = setTimeout(async () => { |
| 69 | // Skip if a save is already in flight |
| 70 | if (isSavingRef.current) { |
| 71 | pendingRef.current = true; |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | isSavingRef.current = true; |
| 76 | try { |
| 77 | const serializable = getSerializableState(state); |
| 78 | await saveWorkspaceState(serializable); |
| 79 | } catch (err) { |
| 80 | const now = Date.now(); |
| 81 | if (now - lastErrorNotifyRef.current >= AUTO_SAVE_ERROR_NOTIFY_MS) { |
| 82 | lastErrorNotifyRef.current = now; |
| 83 | handleApiError(err, 'Auto-save'); |
| 84 | } else { |
| 85 | console.warn('[auto-save] failed:', err); |
| 86 | } |
| 87 | } finally { |
| 88 | isSavingRef.current = false; |
| 89 | // If state changed while we were saving, trigger another save |
| 90 | if (pendingRef.current) { |
| 91 | pendingRef.current = false; |
| 92 | // Re-trigger by scheduling another timeout |
| 93 | timerRef.current = setTimeout(() => { |
| 94 | // This will be picked up by the next effect cycle |
| 95 | }, AUTO_SAVE_DEBOUNCE_MS); |
| 96 | } |
| 97 | } |
| 98 | }, AUTO_SAVE_DEBOUNCE_MS); |
| 99 | |
| 100 | return () => { |
| 101 | if (timerRef.current) { |
| 102 | clearTimeout(timerRef.current); |
| 103 | } |
| 104 | }; |
| 105 | }, [state]); |
| 106 | } |