(
inputValue: string,
setInputValue: (value: InputValue) => void,
options?: {
inputMode?: InputMode
setInputMode?: (mode: InputMode) => void
},
)
| 26 | } |
| 27 | |
| 28 | export const useInputHistory = ( |
| 29 | inputValue: string, |
| 30 | setInputValue: (value: InputValue) => void, |
| 31 | options?: { |
| 32 | inputMode?: InputMode |
| 33 | setInputMode?: (mode: InputMode) => void |
| 34 | }, |
| 35 | ) => { |
| 36 | const { inputMode, setInputMode } = options ?? {} |
| 37 | const messageHistoryRef = useRef<string[]>([]) |
| 38 | const historyIndexRef = useRef<number>(-1) |
| 39 | const currentDraftRef = useRef<string>('') |
| 40 | const currentDraftModeRef = useRef<InputMode>('default') |
| 41 | const isInitializedRef = useRef<boolean>(false) |
| 42 | const isNavigatingRef = useRef<boolean>(false) |
| 43 | |
| 44 | // Load history from disk on mount |
| 45 | useEffect(() => { |
| 46 | if (!isInitializedRef.current) { |
| 47 | isInitializedRef.current = true |
| 48 | const savedHistory = loadMessageHistory() |
| 49 | messageHistoryRef.current = savedHistory |
| 50 | } |
| 51 | }, []) |
| 52 | |
| 53 | const resetHistoryNavigation = useCallback(() => { |
| 54 | historyIndexRef.current = -1 |
| 55 | currentDraftRef.current = '' |
| 56 | currentDraftModeRef.current = 'default' |
| 57 | }, []) |
| 58 | |
| 59 | useEffect(() => { |
| 60 | if (!isNavigatingRef.current) { |
| 61 | resetHistoryNavigation() |
| 62 | } |
| 63 | }, [inputMode, resetHistoryNavigation]) |
| 64 | |
| 65 | const saveToHistory = useCallback((message: string) => { |
| 66 | // Re-read from disk to pick up messages from other terminals |
| 67 | const diskHistory = loadMessageHistory() |
| 68 | const newHistory = [...diskHistory, message] |
| 69 | messageHistoryRef.current = newHistory |
| 70 | historyIndexRef.current = -1 |
| 71 | currentDraftRef.current = '' |
| 72 | currentDraftModeRef.current = 'default' |
| 73 | |
| 74 | // Persist to disk |
| 75 | saveMessageHistory(newHistory) |
| 76 | }, []) |
| 77 | |
| 78 | const navigateUp = useCallback(() => { |
| 79 | const history = messageHistoryRef.current |
| 80 | if (history.length === 0) return |
| 81 | |
| 82 | isNavigatingRef.current = true |
| 83 | |
| 84 | if (historyIndexRef.current === -1) { |
| 85 | // Save current draft and mode before navigating |
no test coverage detected