forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSearchInput.ts
More file actions
364 lines (340 loc) · 10.1 KB
/
useSearchInput.ts
File metadata and controls
364 lines (340 loc) · 10.1 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { useCallback, useState } from 'react'
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 {
Cursor,
getLastKill,
pushToKillRing,
recordYank,
resetKillAccumulation,
resetYankState,
updateYankLength,
yankPop,
} from '../utils/Cursor.js'
import { useTerminalSize } from './useTerminalSize.js'
type UseSearchInputOptions = {
isActive: boolean
onExit: () => void
/** Esc + Ctrl+C abandon (distinct from onExit = Enter commit). When
* provided: single-Esc calls this directly (no clear-first-then-exit
* two-press). When absent: current behavior — Esc clears non-empty
* query, exits on empty; Ctrl+C silently swallowed (no switch case). */
onCancel?: () => void
onExitUp?: () => void
columns?: number
passthroughCtrlKeys?: string[]
initialQuery?: string
/** Backspace (and ctrl+h) on empty query calls onCancel ?? onExit — the
* less/vim "delete past the /" convention. Dialogs that want Esc-only
* cancel set this false so a held backspace doesn't eject the user. */
backspaceExitsOnEmpty?: boolean
}
type UseSearchInputReturn = {
query: string
setQuery: (q: string) => void
cursorOffset: number
handleKeyDown: (e: KeyboardEvent) => void
}
function isKillKey(e: KeyboardEvent): boolean {
if (e.ctrl && (e.key === 'k' || e.key === 'u' || e.key === 'w')) {
return true
}
if (e.meta && e.key === 'backspace') {
return true
}
return false
}
function isYankKey(e: KeyboardEvent): boolean {
return (e.ctrl || e.meta) && e.key === 'y'
}
// Special key names that fall through the explicit handlers above the
// text-input branch (return/escape/arrows/home/end/tab/backspace/delete
// all early-return). Reject these so e.g. PageUp doesn't leak 'pageup'
// as literal text. The length>=1 check below is intentionally loose —
// batched input like stdin.write('abc') arrives as one multi-char e.key,
// matching the old useInput(input) behavior where cursor.insert(input)
// inserted the full chunk.
const UNHANDLED_SPECIAL_KEYS = new Set([
'pageup',
'pagedown',
'insert',
'wheelup',
'wheeldown',
'mouse',
'f1',
'f2',
'f3',
'f4',
'f5',
'f6',
'f7',
'f8',
'f9',
'f10',
'f11',
'f12',
])
export function useSearchInput({
isActive,
onExit,
onCancel,
onExitUp,
columns,
passthroughCtrlKeys = [],
initialQuery = '',
backspaceExitsOnEmpty = true,
}: UseSearchInputOptions): UseSearchInputReturn {
const { columns: terminalColumns } = useTerminalSize()
const effectiveColumns = columns ?? terminalColumns
const [query, setQueryState] = useState(initialQuery)
const [cursorOffset, setCursorOffset] = useState(initialQuery.length)
const setQuery = useCallback((q: string) => {
setQueryState(q)
setCursorOffset(q.length)
}, [])
const handleKeyDown = (e: KeyboardEvent): void => {
if (!isActive) return
const cursor = Cursor.fromText(query, effectiveColumns, cursorOffset)
// Check passthrough ctrl keys
if (e.ctrl && passthroughCtrlKeys.includes(e.key.toLowerCase())) {
return
}
// Reset kill accumulation for non-kill keys
if (!isKillKey(e)) {
resetKillAccumulation()
}
// Reset yank state for non-yank keys
if (!isYankKey(e)) {
resetYankState()
}
// Exit conditions
if (e.key === 'return' || e.key === 'down') {
e.preventDefault()
onExit()
return
}
if (e.key === 'up') {
e.preventDefault()
if (onExitUp) {
onExitUp()
}
return
}
if (e.key === 'escape') {
e.preventDefault()
if (onCancel) {
onCancel()
} else if (query.length > 0) {
setQueryState('')
setCursorOffset(0)
} else {
onExit()
}
return
}
// Backspace/Delete
if (e.key === 'backspace') {
e.preventDefault()
if (e.meta) {
// Meta+Backspace: kill word before
const { cursor: newCursor, killed } = cursor.deleteWordBefore()
pushToKillRing(killed, 'prepend')
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
if (query.length === 0) {
// Backspace past the / — cancel (clear + snap back), not commit.
// less: same. vim: deletes the / and exits command mode.
if (backspaceExitsOnEmpty) (onCancel ?? onExit)()
return
}
const newCursor = cursor.backspace()
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
if (e.key === 'delete') {
e.preventDefault()
const newCursor = cursor.del()
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
// Arrow keys with modifiers (word jump)
if (e.key === 'left' && (e.ctrl || e.meta || e.fn)) {
e.preventDefault()
const newCursor = cursor.prevWord()
setCursorOffset(newCursor.offset)
return
}
if (e.key === 'right' && (e.ctrl || e.meta || e.fn)) {
e.preventDefault()
const newCursor = cursor.nextWord()
setCursorOffset(newCursor.offset)
return
}
// Plain arrow keys
if (e.key === 'left') {
e.preventDefault()
const newCursor = cursor.left()
setCursorOffset(newCursor.offset)
return
}
if (e.key === 'right') {
e.preventDefault()
const newCursor = cursor.right()
setCursorOffset(newCursor.offset)
return
}
// Home/End
if (e.key === 'home') {
e.preventDefault()
setCursorOffset(0)
return
}
if (e.key === 'end') {
e.preventDefault()
setCursorOffset(query.length)
return
}
// Ctrl key bindings
if (e.ctrl) {
e.preventDefault()
switch (e.key.toLowerCase()) {
case 'a':
setCursorOffset(0)
return
case 'e':
setCursorOffset(query.length)
return
case 'b':
setCursorOffset(cursor.left().offset)
return
case 'f':
setCursorOffset(cursor.right().offset)
return
case 'd': {
if (query.length === 0) {
;(onCancel ?? onExit)()
return
}
const newCursor = cursor.del()
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'h': {
if (query.length === 0) {
if (backspaceExitsOnEmpty) (onCancel ?? onExit)()
return
}
const newCursor = cursor.backspace()
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'k': {
const { cursor: newCursor, killed } = cursor.deleteToLineEnd()
pushToKillRing(killed, 'append')
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'u': {
const { cursor: newCursor, killed } = cursor.deleteToLineStart()
pushToKillRing(killed, 'prepend')
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'w': {
const { cursor: newCursor, killed } = cursor.deleteWordBefore()
pushToKillRing(killed, 'prepend')
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'y': {
const text = getLastKill()
if (text.length > 0) {
const startOffset = cursor.offset
const newCursor = cursor.insert(text)
recordYank(startOffset, text.length)
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
}
return
}
case 'g':
case 'c':
// Cancel (abandon search). ctrl+g is less's cancel key. Only
// fires if onCancel provided — otherwise falls through and
// returns silently (11 call sites, most expect ctrl+c to no-op).
if (onCancel) {
onCancel()
return
}
}
return
}
// Meta key bindings
if (e.meta) {
e.preventDefault()
switch (e.key.toLowerCase()) {
case 'b':
setCursorOffset(cursor.prevWord().offset)
return
case 'f':
setCursorOffset(cursor.nextWord().offset)
return
case 'd': {
const newCursor = cursor.deleteWordAfter()
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
return
}
case 'y': {
const popResult = yankPop()
if (popResult) {
const { text, start, length } = popResult
const before = query.slice(0, start)
const after = query.slice(start + length)
const newText = before + text + after
const newOffset = start + text.length
updateYankLength(text.length)
setQueryState(newText)
setCursorOffset(newOffset)
}
return
}
}
return
}
// Tab: ignore
if (e.key === 'tab') {
return
}
// Regular character input. Accepts multi-char e.key so batched writes
// (stdin.write('abc') in tests, or paste outside bracketed-paste mode)
// insert the full chunk — matching the old useInput behavior.
if (e.key.length >= 1 && !UNHANDLED_SPECIAL_KEYS.has(e.key)) {
e.preventDefault()
const newCursor = cursor.insert(e.key)
setQueryState(newCursor.text)
setCursorOffset(newCursor.offset)
}
}
// Backward-compat bridge: existing consumers don't yet wire handleKeyDown
// to <Box onKeyDown>. Subscribe via useInput and adapt InputEvent →
// KeyboardEvent until all 11 call sites are migrated (separate PRs).
// TODO(onKeyDown-migration): remove once all consumers pass handleKeyDown.
useInput(
(_input, _key, event) => {
handleKeyDown(new KeyboardEvent(event.keypress))
},
{ isActive },
)
return { query, setQuery, cursorOffset, handleKeyDown }
}