forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseHistorySearch.ts
More file actions
303 lines (278 loc) · 9.27 KB
/
useHistorySearch.ts
File metadata and controls
303 lines (278 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { feature } from 'bun:bundle'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
getModeFromInput,
getValueFromInput,
} from '../components/PromptInput/inputModes.js'
import { makeHistoryReader } from '../history.js'
import { KeyboardEvent } from '../ink/events/keyboard-event.js'
// eslint-disable-next-line custom-rules/prefer-use-keybindings -- backward-compat bridge until consumers wire handleKeyDown to <Box onKeyDown>
import { useInput } from '../ink.js'
import { useKeybinding, useKeybindings } from '../keybindings/useKeybinding.js'
import type { PromptInputMode } from '../types/textInputTypes.js'
import type { HistoryEntry } from '../utils/config.js'
export function useHistorySearch(
onAcceptHistory: (entry: HistoryEntry) => void,
currentInput: string,
onInputChange: (input: string) => void,
onCursorChange: (cursorOffset: number) => void,
currentCursorOffset: number,
onModeChange: (mode: PromptInputMode) => void,
currentMode: PromptInputMode,
isSearching: boolean,
setIsSearching: (isSearching: boolean) => void,
setPastedContents: (pastedContents: HistoryEntry['pastedContents']) => void,
currentPastedContents: HistoryEntry['pastedContents'],
): {
historyQuery: string
setHistoryQuery: (query: string) => void
historyMatch: HistoryEntry | undefined
historyFailedMatch: boolean
handleKeyDown: (e: KeyboardEvent) => void
} {
const [historyQuery, setHistoryQuery] = useState('')
const [historyFailedMatch, setHistoryFailedMatch] = useState(false)
const [originalInput, setOriginalInput] = useState('')
const [originalCursorOffset, setOriginalCursorOffset] = useState(0)
const [originalMode, setOriginalMode] = useState<PromptInputMode>('prompt')
const [originalPastedContents, setOriginalPastedContents] = useState<
HistoryEntry['pastedContents']
>({})
const [historyMatch, setHistoryMatch] = useState<HistoryEntry | undefined>(
undefined,
)
const historyReader = useRef<AsyncGenerator<HistoryEntry> | undefined>(
undefined,
)
const seenPrompts = useRef<Set<string>>(new Set())
const searchAbortController = useRef<AbortController | null>(null)
const closeHistoryReader = useCallback((): void => {
if (historyReader.current) {
// Must explicitly call .return() to trigger the finally block in readLinesReverse,
// which closes the file handle. Without this, file descriptors leak.
void historyReader.current.return(undefined)
historyReader.current = undefined
}
}, [])
const reset = useCallback((): void => {
setIsSearching(false)
setHistoryQuery('')
setHistoryFailedMatch(false)
setOriginalInput('')
setOriginalCursorOffset(0)
setOriginalMode('prompt')
setOriginalPastedContents({})
setHistoryMatch(undefined)
closeHistoryReader()
seenPrompts.current.clear()
}, [setIsSearching, closeHistoryReader])
const searchHistory = useCallback(
async (resume: boolean, signal?: AbortSignal): Promise<void> => {
if (!isSearching) {
return
}
if (historyQuery.length === 0) {
closeHistoryReader()
seenPrompts.current.clear()
setHistoryMatch(undefined)
setHistoryFailedMatch(false)
onInputChange(originalInput)
onCursorChange(originalCursorOffset)
onModeChange(originalMode)
setPastedContents(originalPastedContents)
return
}
if (!resume) {
closeHistoryReader()
historyReader.current = makeHistoryReader()
seenPrompts.current.clear()
}
if (!historyReader.current) {
return
}
while (true) {
if (signal?.aborted) {
return
}
const item = await historyReader.current.next()
if (item.done) {
// No match found - keep last match but mark as failed
setHistoryFailedMatch(true)
return
}
const display = item.value.display
const matchPosition = display.lastIndexOf(historyQuery)
if (matchPosition !== -1 && !seenPrompts.current.has(display)) {
seenPrompts.current.add(display)
setHistoryMatch(item.value)
setHistoryFailedMatch(false)
const mode = getModeFromInput(display)
onModeChange(mode)
onInputChange(display)
setPastedContents(item.value.pastedContents)
// Position cursor relative to the clean value, not the display
const value = getValueFromInput(display)
const cleanMatchPosition = value.lastIndexOf(historyQuery)
onCursorChange(
cleanMatchPosition !== -1 ? cleanMatchPosition : matchPosition,
)
return
}
}
},
[
isSearching,
historyQuery,
closeHistoryReader,
onInputChange,
onCursorChange,
onModeChange,
setPastedContents,
originalInput,
originalCursorOffset,
originalMode,
originalPastedContents,
],
)
// Handler: Start history search (when not searching)
const handleStartSearch = useCallback(() => {
setIsSearching(true)
setOriginalInput(currentInput)
setOriginalCursorOffset(currentCursorOffset)
setOriginalMode(currentMode)
setOriginalPastedContents(currentPastedContents)
historyReader.current = makeHistoryReader()
seenPrompts.current.clear()
}, [
setIsSearching,
currentInput,
currentCursorOffset,
currentMode,
currentPastedContents,
])
// Handler: Find next match (when searching)
const handleNextMatch = useCallback(() => {
void searchHistory(true)
}, [searchHistory])
// Handler: Accept current match and exit search
const handleAccept = useCallback(() => {
if (historyMatch) {
const mode = getModeFromInput(historyMatch.display)
const value = getValueFromInput(historyMatch.display)
onInputChange(value)
onModeChange(mode)
setPastedContents(historyMatch.pastedContents)
} else {
// No match - restore original pasted contents
setPastedContents(originalPastedContents)
}
reset()
}, [
historyMatch,
onInputChange,
onModeChange,
setPastedContents,
originalPastedContents,
reset,
])
// Handler: Cancel search and restore original input
const handleCancel = useCallback(() => {
onInputChange(originalInput)
onCursorChange(originalCursorOffset)
setPastedContents(originalPastedContents)
reset()
}, [
onInputChange,
onCursorChange,
setPastedContents,
originalInput,
originalCursorOffset,
originalPastedContents,
reset,
])
// Handler: Execute (accept and submit)
const handleExecute = useCallback(() => {
if (historyQuery.length === 0) {
onAcceptHistory({
display: originalInput,
pastedContents: originalPastedContents,
})
} else if (historyMatch) {
const mode = getModeFromInput(historyMatch.display)
const value = getValueFromInput(historyMatch.display)
onModeChange(mode)
onAcceptHistory({
display: value,
pastedContents: historyMatch.pastedContents,
})
}
reset()
}, [
historyQuery,
historyMatch,
onAcceptHistory,
onModeChange,
originalInput,
originalPastedContents,
reset,
])
// Gated off under HISTORY_PICKER — the modal dialog owns ctrl+r there.
useKeybinding('history:search', handleStartSearch, {
context: 'Global',
isActive: feature('HISTORY_PICKER') ? false : !isSearching,
})
// History search context keybindings (only active when searching)
const historySearchHandlers = useMemo(
() => ({
'historySearch:next': handleNextMatch,
'historySearch:accept': handleAccept,
'historySearch:cancel': handleCancel,
'historySearch:execute': handleExecute,
}),
[handleNextMatch, handleAccept, handleCancel, handleExecute],
)
useKeybindings(historySearchHandlers, {
context: 'HistorySearch',
isActive: isSearching,
})
// Handle backspace when query is empty (cancels search)
// This is a conditional behavior that doesn't fit the keybinding model
// well (backspace only cancels when query is empty)
const handleKeyDown = (e: KeyboardEvent): void => {
if (!isSearching) return
if (e.key === 'backspace' && historyQuery === '') {
e.preventDefault()
handleCancel()
}
}
// Backward-compat bridge: PromptInput doesn't yet wire handleKeyDown to
// <Box onKeyDown>. Subscribe via useInput and adapt InputEvent →
// KeyboardEvent until the consumer is migrated (separate PR).
// TODO(onKeyDown-migration): remove once PromptInput passes handleKeyDown.
useInput(
(_input, _key, event) => {
handleKeyDown(new KeyboardEvent(event.keypress))
},
{ isActive: isSearching },
)
// Keep a ref to searchHistory to avoid it being a dependency of useEffect
const searchHistoryRef = useRef(searchHistory)
searchHistoryRef.current = searchHistory
// Reset history search when query changes
useEffect(() => {
searchAbortController.current?.abort()
const controller = new AbortController()
searchAbortController.current = controller
void searchHistoryRef.current(false, controller.signal)
return () => {
controller.abort()
}
}, [historyQuery])
return {
historyQuery,
setHistoryQuery,
historyMatch,
historyFailedMatch,
handleKeyDown,
}
}