|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Porpoiseful LLC |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @fileoverview Autosave manager that tracks unsaved changes and triggers saves. |
| 20 | + * @author alan@porpoiseful.com (Alan Smith) |
| 21 | + */ |
| 22 | +import * as React from 'react'; |
| 23 | + |
| 24 | +/** Delay in milliseconds before auto-saving after a change. */ |
| 25 | +const AUTOSAVE_DELAY_MS = 5000; |
| 26 | + |
| 27 | +/** Context for autosave state. */ |
| 28 | +interface AutosaveContextType { |
| 29 | + /** Whether the current tab has unsaved changes. */ |
| 30 | + hasUnsavedChanges: boolean; |
| 31 | + /** Mark the current tab as having unsaved changes. */ |
| 32 | + markAsModified: () => void; |
| 33 | + /** Mark the current tab as saved. */ |
| 34 | + markAsSaved: () => void; |
| 35 | + /** Trigger an immediate save of the current tab. */ |
| 36 | + triggerSave: () => Promise<void>; |
| 37 | +} |
| 38 | + |
| 39 | +const AutosaveContext = React.createContext<AutosaveContextType | null>(null); |
| 40 | + |
| 41 | +/** Props for AutosaveProvider. */ |
| 42 | +interface AutosaveProviderProps { |
| 43 | + children: React.ReactNode; |
| 44 | + /** Function to save the current active tab. */ |
| 45 | + saveCurrentTab: () => Promise<void>; |
| 46 | + /** Current active tab key. */ |
| 47 | + activeTabKey: string; |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Provider component that manages autosave state and triggers. |
| 52 | + * Handles debounced auto-save after changes. |
| 53 | + */ |
| 54 | +export function AutosaveProvider({ children, saveCurrentTab, activeTabKey }: AutosaveProviderProps): React.JSX.Element { |
| 55 | + const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false); |
| 56 | + const [lastActiveTabKey, setLastActiveTabKey] = React.useState(activeTabKey); |
| 57 | + const saveTimerRef = React.useRef<NodeJS.Timeout | null>(null); |
| 58 | + |
| 59 | + /** Clears any pending autosave timer. */ |
| 60 | + const clearSaveTimer = React.useCallback(() => { |
| 61 | + if (saveTimerRef.current) { |
| 62 | + clearTimeout(saveTimerRef.current); |
| 63 | + saveTimerRef.current = null; |
| 64 | + } |
| 65 | + }, []); |
| 66 | + |
| 67 | + /** Marks the current tab as having unsaved changes and schedules an autosave. */ |
| 68 | + const markAsModified = React.useCallback(() => { |
| 69 | + setHasUnsavedChanges(true); |
| 70 | + |
| 71 | + // Clear any existing timer |
| 72 | + clearSaveTimer(); |
| 73 | + |
| 74 | + // Schedule a new autosave |
| 75 | + saveTimerRef.current = setTimeout(async () => { |
| 76 | + try { |
| 77 | + await saveCurrentTab(); |
| 78 | + setHasUnsavedChanges(false); |
| 79 | + } catch (error) { |
| 80 | + console.error('Autosave failed:', error); |
| 81 | + // Keep hasUnsavedChanges true on error |
| 82 | + } |
| 83 | + }, AUTOSAVE_DELAY_MS); |
| 84 | + }, [saveCurrentTab, clearSaveTimer]); |
| 85 | + |
| 86 | + /** Marks the current tab as saved. */ |
| 87 | + const markAsSaved = React.useCallback(() => { |
| 88 | + setHasUnsavedChanges(false); |
| 89 | + clearSaveTimer(); |
| 90 | + }, [clearSaveTimer]); |
| 91 | + |
| 92 | + /** Triggers an immediate save. */ |
| 93 | + const triggerSave = React.useCallback(async () => { |
| 94 | + clearSaveTimer(); |
| 95 | + try { |
| 96 | + await saveCurrentTab(); |
| 97 | + setHasUnsavedChanges(false); |
| 98 | + } catch (error) { |
| 99 | + console.error('Manual save failed:', error); |
| 100 | + throw error; |
| 101 | + } |
| 102 | + }, [saveCurrentTab, clearSaveTimer]); |
| 103 | + |
| 104 | + // When tab changes, clear unsaved state for the new tab |
| 105 | + React.useEffect(() => { |
| 106 | + if (activeTabKey !== lastActiveTabKey) { |
| 107 | + setHasUnsavedChanges(false); |
| 108 | + setLastActiveTabKey(activeTabKey); |
| 109 | + } |
| 110 | + }, [activeTabKey, lastActiveTabKey]); |
| 111 | + |
| 112 | + // Cleanup on unmount |
| 113 | + React.useEffect(() => { |
| 114 | + return () => { |
| 115 | + clearSaveTimer(); |
| 116 | + }; |
| 117 | + }, [clearSaveTimer]); |
| 118 | + |
| 119 | + const contextValue: AutosaveContextType = { |
| 120 | + hasUnsavedChanges, |
| 121 | + markAsModified, |
| 122 | + markAsSaved, |
| 123 | + triggerSave, |
| 124 | + }; |
| 125 | + |
| 126 | + return ( |
| 127 | + <AutosaveContext.Provider value={contextValue}> |
| 128 | + {children} |
| 129 | + </AutosaveContext.Provider> |
| 130 | + ); |
| 131 | +} |
| 132 | + |
| 133 | +/** |
| 134 | + * Hook to access autosave context. |
| 135 | + * @returns Autosave context value. |
| 136 | + * @throws Error if used outside of AutosaveProvider. |
| 137 | + */ |
| 138 | +export function useAutosave(): AutosaveContextType { |
| 139 | + const context = React.useContext(AutosaveContext); |
| 140 | + if (!context) { |
| 141 | + throw new Error('useAutosave must be used within AutosaveProvider'); |
| 142 | + } |
| 143 | + return context; |
| 144 | +} |
0 commit comments