|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import { useState, useCallback } from 'react'; |
|
|
|
|
|
interface UseInputHistoryProps { |
|
|
userMessages: readonly string[]; |
|
|
onSubmit: (value: string) => void; |
|
|
isActive: boolean; |
|
|
currentQuery: string; |
|
|
onChange: (value: string) => void; |
|
|
} |
|
|
|
|
|
export interface UseInputHistoryReturn { |
|
|
handleSubmit: (value: string) => void; |
|
|
navigateUp: () => boolean; |
|
|
navigateDown: () => boolean; |
|
|
} |
|
|
|
|
|
export function useInputHistory({ |
|
|
userMessages, |
|
|
onSubmit, |
|
|
isActive, |
|
|
currentQuery, |
|
|
onChange, |
|
|
}: UseInputHistoryProps): UseInputHistoryReturn { |
|
|
const [historyIndex, setHistoryIndex] = useState<number>(-1); |
|
|
const [originalQueryBeforeNav, setOriginalQueryBeforeNav] = |
|
|
useState<string>(''); |
|
|
|
|
|
const resetHistoryNav = useCallback(() => { |
|
|
setHistoryIndex(-1); |
|
|
setOriginalQueryBeforeNav(''); |
|
|
}, []); |
|
|
|
|
|
const handleSubmit = useCallback( |
|
|
(value: string) => { |
|
|
const trimmedValue = value.trim(); |
|
|
if (trimmedValue) { |
|
|
onSubmit(trimmedValue); |
|
|
} |
|
|
resetHistoryNav(); |
|
|
}, |
|
|
[onSubmit, resetHistoryNav], |
|
|
); |
|
|
|
|
|
const navigateUp = useCallback(() => { |
|
|
if (!isActive) return false; |
|
|
if (userMessages.length === 0) return false; |
|
|
|
|
|
let nextIndex = historyIndex; |
|
|
if (historyIndex === -1) { |
|
|
|
|
|
setOriginalQueryBeforeNav(currentQuery); |
|
|
nextIndex = 0; |
|
|
} else if (historyIndex < userMessages.length - 1) { |
|
|
nextIndex = historyIndex + 1; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
|
|
|
if (nextIndex !== historyIndex) { |
|
|
setHistoryIndex(nextIndex); |
|
|
const newValue = userMessages[userMessages.length - 1 - nextIndex]; |
|
|
onChange(newValue); |
|
|
return true; |
|
|
} |
|
|
return false; |
|
|
}, [ |
|
|
historyIndex, |
|
|
setHistoryIndex, |
|
|
onChange, |
|
|
userMessages, |
|
|
isActive, |
|
|
currentQuery, |
|
|
setOriginalQueryBeforeNav, |
|
|
]); |
|
|
|
|
|
const navigateDown = useCallback(() => { |
|
|
if (!isActive) return false; |
|
|
if (historyIndex === -1) return false; |
|
|
|
|
|
const nextIndex = historyIndex - 1; |
|
|
setHistoryIndex(nextIndex); |
|
|
|
|
|
if (nextIndex === -1) { |
|
|
|
|
|
onChange(originalQueryBeforeNav); |
|
|
} else { |
|
|
const newValue = userMessages[userMessages.length - 1 - nextIndex]; |
|
|
onChange(newValue); |
|
|
} |
|
|
return true; |
|
|
}, [ |
|
|
historyIndex, |
|
|
setHistoryIndex, |
|
|
originalQueryBeforeNav, |
|
|
onChange, |
|
|
userMessages, |
|
|
isActive, |
|
|
]); |
|
|
|
|
|
return { |
|
|
handleSubmit, |
|
|
navigateUp, |
|
|
navigateDown, |
|
|
}; |
|
|
} |
|
|
|