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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import React, { useCallback } from 'react';
import { Text, Box, useInput, useStdin } from 'ink';
import { Colors } from '../colors.js';
import { SuggestionsDisplay } from './SuggestionsDisplay.js';
import { useInputHistory } from '../hooks/useInputHistory.js';
import { useTextBuffer, cpSlice, cpLen } from './shared/text-buffer.js';
import chalk from 'chalk';
import { useTerminalSize } from '../hooks/useTerminalSize.js';
import stringWidth from 'string-width';
import process from 'node:process';
import { useCompletion } from '../hooks/useCompletion.js';
import { isAtCommand, isSlashCommand } from '../utils/commandUtils.js';
import { SlashCommand } from '../hooks/slashCommandProcessor.js';
import { Config } from '@gemini-code/server';
interface InputPromptProps {
onSubmit: (value: string) => void;
userMessages: readonly string[];
onClearScreen: () => void;
config: Config; // Added config for useCompletion
slashCommands: SlashCommand[]; // Added slashCommands for useCompletion
placeholder?: string;
height?: number; // Visible height of the editor area
focus?: boolean;
widthFraction: number;
shellModeActive: boolean;
setShellModeActive: (value: boolean) => void;
}
export const InputPrompt: React.FC<InputPromptProps> = ({
onSubmit,
userMessages,
onClearScreen,
config,
slashCommands,
placeholder = 'Enter your message or use tools (e.g., @src/file.txt)...',
height = 10,
focus = true,
widthFraction,
shellModeActive,
setShellModeActive,
}) => {
const terminalSize = useTerminalSize();
const padding = 3;
const effectiveWidth = Math.max(
20,
Math.round(terminalSize.columns * widthFraction) - padding,
);
const suggestionsWidth = Math.max(60, Math.floor(terminalSize.columns * 0.8));
const { stdin, setRawMode } = useStdin();
const buffer = useTextBuffer({
initialText: '',
viewport: { height, width: effectiveWidth },
stdin,
setRawMode,
});
const completion = useCompletion(
buffer.text,
config.getTargetDir(),
isAtCommand(buffer.text) || isSlashCommand(buffer.text),
slashCommands,
);
const resetCompletionState = completion.resetCompletionState;
const handleSubmitAndClear = useCallback(
(submittedValue: string) => {
onSubmit(submittedValue);
buffer.setText('');
resetCompletionState();
},
[onSubmit, buffer, resetCompletionState],
);
const onChangeAndMoveCursor = useCallback(
(newValue: string) => {
buffer.setText(newValue);
buffer.move('end');
},
[buffer],
);
const inputHistory = useInputHistory({
userMessages,
onSubmit: handleSubmitAndClear,
isActive: !completion.showSuggestions,
currentQuery: buffer.text,
onChangeAndMoveCursor,
});
const completionSuggestions = completion.suggestions;
const handleAutocomplete = useCallback(
(indexToUse: number) => {
if (indexToUse < 0 || indexToUse >= completionSuggestions.length) {
return;
}
const query = buffer.text;
const selectedSuggestion = completionSuggestions[indexToUse];
if (query.trimStart().startsWith('/')) {
const slashIndex = query.indexOf('/');
const base = query.substring(0, slashIndex + 1);
const newValue = base + selectedSuggestion.value;
buffer.setText(newValue);
handleSubmitAndClear(newValue);
} else {
const atIndex = query.lastIndexOf('@');
if (atIndex === -1) return;
const pathPart = query.substring(atIndex + 1);
const lastSlashIndexInPath = pathPart.lastIndexOf('/');
let autoCompleteStartIndex = atIndex + 1;
if (lastSlashIndexInPath !== -1) {
autoCompleteStartIndex += lastSlashIndexInPath + 1;
}
buffer.replaceRangeByOffset(
autoCompleteStartIndex,
buffer.text.length,
selectedSuggestion.value,
);
}
resetCompletionState();
},
[resetCompletionState, handleSubmitAndClear, buffer, completionSuggestions],
);
useInput(
(input, key) => {
if (!focus) {
return;
}
const query = buffer.text;
if (input === '!' && query === '' && !completion.showSuggestions) {
setShellModeActive(!shellModeActive);
buffer.setText(''); // Clear the '!' from input
return true;
}
if (completion.showSuggestions) {
if (key.upArrow) {
completion.navigateUp();
return;
}
if (key.downArrow) {
completion.navigateDown();
return;
}
if (key.tab) {
if (completion.suggestions.length > 0) {
const targetIndex =
completion.activeSuggestionIndex === -1
? 0
: completion.activeSuggestionIndex;
if (targetIndex < completion.suggestions.length) {
handleAutocomplete(targetIndex);
}
}
return;
}
if (key.return) {
if (completion.activeSuggestionIndex >= 0) {
handleAutocomplete(completion.activeSuggestionIndex);
} else if (query.trim()) {
handleSubmitAndClear(query);
}
return;
}
} else {
// Keybindings when suggestions are not shown
if (key.ctrl && input === 'l') {
onClearScreen();
return true;
}
if (key.ctrl && input === 'p') {
inputHistory.navigateUp();
return true;
}
if (key.ctrl && input === 'n') {
inputHistory.navigateDown();
return true;
}
if (key.escape) {
completion.resetCompletionState();
return;
}
}
// Ctrl+A (Home)
if (key.ctrl && input === 'a') {
buffer.move('home');
buffer.moveToOffset(0);
return;
}
// Ctrl+E (End)
if (key.ctrl && input === 'e') {
buffer.move('end');
buffer.moveToOffset(cpLen(buffer.text));
return;
}
// Ctrl+L (Clear Screen)
if (key.ctrl && input === 'l') {
onClearScreen();
return;
}
// Ctrl+P (History Up)
if (key.ctrl && input === 'p' && !completion.showSuggestions) {
inputHistory.navigateUp();
return;
}
// Ctrl+N (History Down)
if (key.ctrl && input === 'n' && !completion.showSuggestions) {
inputHistory.navigateDown();
return;
}
// Core text editing from MultilineTextEditor's useInput
if (key.ctrl && input === 'k') {
buffer.killLineRight();
return;
}
if (key.ctrl && input === 'u') {
buffer.killLineLeft();
return;
}
const isCtrlX =
(key.ctrl && (input === 'x' || input === '\x18')) || input === '\x18';
const isCtrlEFromEditor =
(key.ctrl && (input === 'e' || input === '\x05')) ||
input === '\x05' ||
(!key.ctrl &&
input === 'e' &&
input.length === 1 &&
input.charCodeAt(0) === 5);
if (isCtrlX || isCtrlEFromEditor) {
if (isCtrlEFromEditor && !(key.ctrl && input === 'e')) {
// Avoid double handling Ctrl+E
buffer.openInExternalEditor();
return;
}
if (isCtrlX) {
buffer.openInExternalEditor();
return;
}
}
if (
process.env['TEXTBUFFER_DEBUG'] === '1' ||
process.env['TEXTBUFFER_DEBUG'] === 'true'
) {
console.log('[InputPromptCombined] event', { input, key });
}
// Ctrl+Enter for newline, Enter for submit
if (key.return) {
if (key.ctrl) {
// Ctrl+Enter for newline
buffer.newline();
} else {
// Enter for submit
if (query.trim()) {
handleSubmitAndClear(query);
}
}
return;
}
// Standard arrow navigation within the buffer
if (key.upArrow && !completion.showSuggestions) {
if (
buffer.visualCursor[0] === 0 &&
buffer.visualScrollRow === 0 &&
inputHistory.navigateUp
) {
inputHistory.navigateUp();
} else {
buffer.move('up');
}
return;
}
if (key.downArrow && !completion.showSuggestions) {
if (
buffer.visualCursor[0] === buffer.allVisualLines.length - 1 &&
inputHistory.navigateDown
) {
inputHistory.navigateDown();
} else {
buffer.move('down');
}
return;
}
// Fallback to buffer's default input handling
buffer.handleInput(input, key as Record<string, boolean>);
},
{
isActive: focus,
},
);
const linesToRender = buffer.viewportVisualLines;
const [cursorVisualRowAbsolute, cursorVisualColAbsolute] =
buffer.visualCursor;
const scrollVisualRow = buffer.visualScrollRow;
return (
<>
<Box
borderStyle="round"
borderColor={shellModeActive ? Colors.AccentYellow : Colors.AccentBlue}
paddingX={1}
>
<Text
color={shellModeActive ? Colors.AccentYellow : Colors.AccentPurple}
>
{shellModeActive ? '! ' : '> '}
</Text>
<Box flexGrow={1} flexDirection="column">
{buffer.text.length === 0 && placeholder ? (
<Text color={Colors.SubtleComment}>{placeholder}</Text>
) : (
linesToRender.map((lineText, visualIdxInRenderedSet) => {
const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
let display = cpSlice(lineText, 0, effectiveWidth);
const currentVisualWidth = stringWidth(display);
if (currentVisualWidth < effectiveWidth) {
display =
display + ' '.repeat(effectiveWidth - currentVisualWidth);
}
if (visualIdxInRenderedSet === cursorVisualRow) {
const relativeVisualColForHighlight = cursorVisualColAbsolute;
if (relativeVisualColForHighlight >= 0) {
if (relativeVisualColForHighlight < cpLen(display)) {
const charToHighlight =
cpSlice(
display,
relativeVisualColForHighlight,
relativeVisualColForHighlight + 1,
) || ' ';
const highlighted = chalk.inverse(charToHighlight);
display =
cpSlice(display, 0, relativeVisualColForHighlight) +
highlighted +
cpSlice(display, relativeVisualColForHighlight + 1);
} else if (
relativeVisualColForHighlight === cpLen(display) &&
cpLen(display) === effectiveWidth
) {
display = display + chalk.inverse(' ');
}
}
}
return (
<Text key={`line-${visualIdxInRenderedSet}`}>{display}</Text>
);
})
)}
</Box>
</Box>
{completion.showSuggestions && (
<Box>
<SuggestionsDisplay
suggestions={completion.suggestions}
activeIndex={completion.activeSuggestionIndex}
isLoading={completion.isLoadingSuggestions}
width={suggestionsWidth}
scrollOffset={completion.visibleStartIndex}
userInput={buffer.text}
/>
</Box>
)}
</>
);
};
|