/ src / hooks / useArrowKeyHistory.ts
useArrowKeyHistory.ts
 1  import { useState } from 'react'
 2  import { getHistory } from '../history.js'
 3  
 4  export function useArrowKeyHistory(
 5    onSetInput: (value: string, mode: 'bash' | 'prompt') => void,
 6    currentInput: string,
 7  ) {
 8    const [historyIndex, setHistoryIndex] = useState(0)
 9    const [lastTypedInput, setLastTypedInput] = useState('')
10  
11    const updateInput = (input: string | undefined) => {
12      if (input !== undefined) {
13        const mode = input.startsWith('!') ? 'bash' : 'prompt'
14        const value = mode === 'bash' ? input.slice(1) : input
15        onSetInput(value, mode)
16      }
17    }
18  
19    function onHistoryUp() {
20      const latestHistory = getHistory()
21      if (historyIndex < latestHistory.length) {
22        if (historyIndex === 0 && currentInput.trim() !== '') {
23          setLastTypedInput(currentInput)
24        }
25        const newIndex = historyIndex + 1
26        setHistoryIndex(newIndex)
27        updateInput(latestHistory[historyIndex])
28      }
29    }
30  
31    function onHistoryDown() {
32      const latestHistory = getHistory()
33      if (historyIndex > 1) {
34        const newIndex = historyIndex - 1
35        setHistoryIndex(newIndex)
36        updateInput(latestHistory[newIndex - 1])
37      } else if (historyIndex === 1) {
38        setHistoryIndex(0)
39        updateInput(lastTypedInput)
40      }
41    }
42  
43    function resetHistory() {
44      setLastTypedInput('')
45      setHistoryIndex(0)
46    }
47  
48    return {
49      historyIndex,
50      setHistoryIndex,
51      onHistoryUp,
52      onHistoryDown,
53      resetHistory,
54    }
55  }