|
| 1 | +import { useEffect, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +export type FieldSaveState = 'idle' | 'saving' | 'saved' | 'error'; |
| 4 | + |
| 5 | +interface UseFieldAutosaveOpts<T> { |
| 6 | + /** Current value from the page's form state. */ |
| 7 | + value: T; |
| 8 | + /** True once the initial GET has populated the form — prevents the hook |
| 9 | + * from firing a PATCH the moment the page finishes loading. */ |
| 10 | + isLoaded: boolean; |
| 11 | + /** Called when the hook decides the value differs from the last-persisted |
| 12 | + * value. Should resolve on success, throw on failure. */ |
| 13 | + persist: (value: T) => Promise<void>; |
| 14 | + /** Debounce window in ms. Text / number → ~600ms; switches and selects |
| 15 | + * pass 0 so the save fires as soon as the user commits. */ |
| 16 | + debounceMs?: number; |
| 17 | +} |
| 18 | + |
| 19 | +/// Inline-save for a single scalar setting. The hook watches `value`, and |
| 20 | +/// when it diverges from the last-persisted snapshot it schedules a |
| 21 | +/// debounced PATCH. State transitions: idle → saving → saved → idle (after |
| 22 | +/// a short acknowledgement window) or → error (which sticks until the |
| 23 | +/// next successful save). |
| 24 | +export function useFieldAutosave<T>({ |
| 25 | + value, |
| 26 | + isLoaded, |
| 27 | + persist, |
| 28 | + debounceMs = 600, |
| 29 | +}: UseFieldAutosaveOpts<T>): { state: FieldSaveState; error: string | null } { |
| 30 | + const [state, setState] = useState<FieldSaveState>('idle'); |
| 31 | + const [error, setError] = useState<string | null>(null); |
| 32 | + |
| 33 | + // `persist` gets re-created on every render from the caller (inline |
| 34 | + // arrow), so we capture it in a ref instead of depending on it in the |
| 35 | + // effect — otherwise the timer would restart every render and never |
| 36 | + // actually fire. |
| 37 | + const persistRef = useRef(persist); |
| 38 | + persistRef.current = persist; |
| 39 | + |
| 40 | + // Snapshot of the last value the server acknowledged. Seeded on first |
| 41 | + // load so the hook doesn't interpret "page just populated" as a change. |
| 42 | + const lastSavedRef = useRef<T | null>(null); |
| 43 | + const seededRef = useRef(false); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + if (!isLoaded) return; |
| 47 | + if (!seededRef.current) { |
| 48 | + lastSavedRef.current = value; |
| 49 | + seededRef.current = true; |
| 50 | + return; |
| 51 | + } |
| 52 | + if (value === lastSavedRef.current) { |
| 53 | + // Reverted to the saved value — cancel any pending acknowledgement |
| 54 | + // so the field doesn't flicker a stale ✓. |
| 55 | + setState('idle'); |
| 56 | + setError(null); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + const id = setTimeout(async () => { |
| 61 | + setState('saving'); |
| 62 | + setError(null); |
| 63 | + try { |
| 64 | + await persistRef.current(value); |
| 65 | + lastSavedRef.current = value; |
| 66 | + setState('saved'); |
| 67 | + // Clear the ✓ after a beat so the row settles back to calm. |
| 68 | + setTimeout(() => { |
| 69 | + setState((s) => (s === 'saved' ? 'idle' : s)); |
| 70 | + }, 1500); |
| 71 | + } catch (err) { |
| 72 | + setState('error'); |
| 73 | + setError(err instanceof Error ? err.message : 'Save failed'); |
| 74 | + } |
| 75 | + }, debounceMs); |
| 76 | + |
| 77 | + return () => clearTimeout(id); |
| 78 | + }, [value, isLoaded, debounceMs]); |
| 79 | + |
| 80 | + return { state, error }; |
| 81 | +} |
0 commit comments