Merge InputPrompt and multiline-editor and move autocomplete logic directly into InputPrompt (#453)

This commit is contained in:
Jacob Richman 2025-05-20 16:50:32 -07:00 committed by GitHub
parent 937f473651
commit 02ab0c234c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 598 additions and 459 deletions

View File

@ -17,7 +17,7 @@ import { Header } from './components/Header.js';
import { LoadingIndicator } from './components/LoadingIndicator.js'; import { LoadingIndicator } from './components/LoadingIndicator.js';
import { AutoAcceptIndicator } from './components/AutoAcceptIndicator.js'; import { AutoAcceptIndicator } from './components/AutoAcceptIndicator.js';
import { ShellModeIndicator } from './components/ShellModeIndicator.js'; import { ShellModeIndicator } from './components/ShellModeIndicator.js';
import { EditorState, InputPrompt } from './components/InputPrompt.js'; import { InputPrompt } from './components/InputPrompt.js';
import { Footer } from './components/Footer.js'; import { Footer } from './components/Footer.js';
import { ThemeDialog } from './components/ThemeDialog.js'; import { ThemeDialog } from './components/ThemeDialog.js';
import { type Config } from '@gemini-code/server'; import { type Config } from '@gemini-code/server';
@ -28,9 +28,6 @@ import { LoadedSettings } from '../config/settings.js';
import { Tips } from './components/Tips.js'; import { Tips } from './components/Tips.js';
import { ConsoleOutput } from './components/ConsolePatcher.js'; import { ConsoleOutput } from './components/ConsolePatcher.js';
import { HistoryItemDisplay } from './components/HistoryItemDisplay.js'; import { HistoryItemDisplay } from './components/HistoryItemDisplay.js';
import { useCompletion } from './hooks/useCompletion.js';
import { SuggestionsDisplay } from './components/SuggestionsDisplay.js';
import { isAtCommand, isSlashCommand } from './utils/commandUtils.js';
import { useHistory } from './hooks/useHistoryManager.js'; import { useHistory } from './hooks/useHistoryManager.js';
import process from 'node:process'; // For performMemoryRefresh import process from 'node:process'; // For performMemoryRefresh
import { MessageType } from './types.js'; // For performMemoryRefresh import { MessageType } from './types.js'; // For performMemoryRefresh
@ -99,7 +96,6 @@ export const App = ({
config.setGeminiMdFileCount(fileCount); config.setGeminiMdFileCount(fileCount);
setGeminiMdFileCount(fileCount); setGeminiMdFileCount(fileCount);
// chatSessionRef.current = null; // This was in useGeminiStream, might need similar logic or pass chat ref
addItem( addItem(
{ {
type: MessageType.INFO, type: MessageType.INFO,
@ -126,7 +122,7 @@ export const App = ({
}, [config, addItem]); }, [config, addItem]);
const { handleSlashCommand, slashCommands } = useSlashCommandProcessor( const { handleSlashCommand, slashCommands } = useSlashCommandProcessor(
config, // Pass config config,
addItem, addItem,
clearItems, clearItems,
refreshStatic, refreshStatic,
@ -176,53 +172,24 @@ export const App = ({
const isInputActive = streamingState === StreamingState.Idle && !initError; const isInputActive = streamingState === StreamingState.Idle && !initError;
const [query, setQuery] = useState('');
const [editorState, setEditorState] = useState<EditorState>({
key: 0,
initialCursorOffset: undefined,
});
const onChangeAndMoveCursor = useCallback(
(value: string) => {
setQuery(value);
setEditorState((s) => ({
key: s.key + 1,
initialCursorOffset: value.length,
}));
},
[setQuery, setEditorState],
);
const handleClearScreen = useCallback(() => { const handleClearScreen = useCallback(() => {
clearItems(); clearItems();
console.clear(); console.clear();
refreshStatic(); refreshStatic();
}, [clearItems, refreshStatic]); }, [clearItems, refreshStatic]);
const completion = useCompletion(
query,
config.getTargetDir(),
!shellModeActive &&
isInputActive &&
(isAtCommand(query) || isSlashCommand(query)),
slashCommands,
);
// --- Render Logic --- // --- Render Logic ---
const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize(); const { rows: terminalHeight } = useTerminalSize();
const mainControlsRef = useRef<DOMElement>(null); const mainControlsRef = useRef<DOMElement>(null);
const pendingHistoryItemRef = useRef<DOMElement>(null); const pendingHistoryItemRef = useRef<DOMElement>(null);
// Calculate width for suggestions, leave some padding
const suggestionsWidth = Math.max(60, Math.floor(terminalWidth * 0.8));
useEffect(() => { useEffect(() => {
if (mainControlsRef.current) { if (mainControlsRef.current) {
const fullFooterMeasurement = measureElement(mainControlsRef.current); const fullFooterMeasurement = measureElement(mainControlsRef.current);
setFooterHeight(fullFooterMeasurement.height); setFooterHeight(fullFooterMeasurement.height);
} }
}, [terminalHeight]); // Re-calculate if terminalHeight changes, as it might affect footer's rendered height. }, [terminalHeight]);
const availableTerminalHeight = useMemo(() => { const availableTerminalHeight = useMemo(() => {
const staticExtraHeight = /* margins and padding */ 3; const staticExtraHeight = /* margins and padding */ 3;
@ -326,7 +293,6 @@ export const App = ({
onSelect={handleThemeSelect} onSelect={handleThemeSelect}
onHighlight={handleThemeHighlight} onHighlight={handleThemeHighlight}
settings={settings} settings={settings}
setQuery={setQuery}
/> />
</Box> </Box>
) : ( ) : (
@ -361,37 +327,16 @@ export const App = ({
</Box> </Box>
</Box> </Box>
{isInputActive && ( {isInputActive && (
<> <InputPrompt
<InputPrompt widthFraction={0.9}
query={query} onSubmit={handleFinalSubmit}
onChange={setQuery} userMessages={userMessages}
onChangeAndMoveCursor={onChangeAndMoveCursor} onClearScreen={handleClearScreen}
editorState={editorState} config={config}
onSubmit={handleFinalSubmit} // Pass handleFinalSubmit directly slashCommands={slashCommands}
showSuggestions={completion.showSuggestions} shellModeActive={shellModeActive}
suggestions={completion.suggestions} setShellModeActive={setShellModeActive}
activeSuggestionIndex={completion.activeSuggestionIndex} />
userMessages={userMessages} // Pass userMessages
navigateSuggestionUp={completion.navigateUp}
navigateSuggestionDown={completion.navigateDown}
resetCompletion={completion.resetCompletionState}
onClearScreen={handleClearScreen} // Added onClearScreen prop
shellModeActive={shellModeActive}
setShellModeActive={setShellModeActive}
/>
{completion.showSuggestions && !shellModeActive && (
<Box>
<SuggestionsDisplay
suggestions={completion.suggestions}
activeIndex={completion.activeSuggestionIndex}
isLoading={completion.isLoadingSuggestions}
width={suggestionsWidth}
scrollOffset={completion.visibleStartIndex}
userInput={query}
/>
</Box>
)}
</>
)} )}
</> </>
)} )}

View File

@ -5,147 +5,174 @@
*/ */
import React, { useCallback } from 'react'; import React, { useCallback } from 'react';
import { Text, Box, Key } from 'ink'; import { Text, Box, useInput, useStdin } from 'ink';
import { Colors } from '../colors.js'; import { Colors } from '../colors.js';
import { Suggestion } from './SuggestionsDisplay.js'; import { SuggestionsDisplay } from './SuggestionsDisplay.js';
import { MultilineTextEditor } from './shared/multiline-editor.js';
import { useInputHistory } from '../hooks/useInputHistory.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 { interface InputPromptProps {
query: string;
onChange: (value: string) => void;
onChangeAndMoveCursor: (value: string) => void;
editorState: EditorState;
onSubmit: (value: string) => void; onSubmit: (value: string) => void;
showSuggestions: boolean;
suggestions: Suggestion[];
activeSuggestionIndex: number;
resetCompletion: () => void;
userMessages: readonly string[]; userMessages: readonly string[];
navigateSuggestionUp: () => void;
navigateSuggestionDown: () => void;
onClearScreen: () => void; 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; shellModeActive: boolean;
setShellModeActive: (value: boolean) => void; setShellModeActive: (value: boolean) => void;
} }
export interface EditorState {
key: number;
initialCursorOffset?: number;
}
export const InputPrompt: React.FC<InputPromptProps> = ({ export const InputPrompt: React.FC<InputPromptProps> = ({
query,
onChange,
onChangeAndMoveCursor,
editorState,
onSubmit, onSubmit,
showSuggestions,
suggestions,
activeSuggestionIndex,
userMessages, userMessages,
navigateSuggestionUp,
navigateSuggestionDown,
resetCompletion,
onClearScreen, onClearScreen,
config,
slashCommands,
placeholder = 'Enter your message or use tools (e.g., @src/file.txt)...',
height = 10,
focus = true,
widthFraction,
shellModeActive, shellModeActive,
setShellModeActive, setShellModeActive,
}) => { }) => {
const handleSubmit = useCallback( 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) => { (submittedValue: string) => {
onSubmit(submittedValue); onSubmit(submittedValue);
onChangeAndMoveCursor(''); // Clear query after submit buffer.setText('');
resetCompletionState();
}, },
[onSubmit, onChangeAndMoveCursor], [onSubmit, buffer, resetCompletionState],
);
const onChangeAndMoveCursor = useCallback(
(newValue: string) => {
buffer.setText(newValue);
buffer.move('end');
},
[buffer],
); );
const inputHistory = useInputHistory({ const inputHistory = useInputHistory({
userMessages, userMessages,
onSubmit: handleSubmit, onSubmit: handleSubmitAndClear,
isActive: !showSuggestions, // Input history is active when suggestions are not shown isActive: !completion.showSuggestions,
currentQuery: query, currentQuery: buffer.text,
onChangeAndMoveCursor, onChangeAndMoveCursor,
}); });
const completionSuggestions = completion.suggestions;
const handleAutocomplete = useCallback( const handleAutocomplete = useCallback(
(indexToUse: number) => { (indexToUse: number) => {
if (indexToUse < 0 || indexToUse >= suggestions.length) { if (indexToUse < 0 || indexToUse >= completionSuggestions.length) {
return; return;
} }
const selectedSuggestion = suggestions[indexToUse]; const query = buffer.text;
const trimmedQuery = query.trimStart(); const selectedSuggestion = completionSuggestions[indexToUse];
if (trimmedQuery.startsWith('/')) { if (query.trimStart().startsWith('/')) {
// Handle / command completion
const slashIndex = query.indexOf('/'); const slashIndex = query.indexOf('/');
const base = query.substring(0, slashIndex + 1); const base = query.substring(0, slashIndex + 1);
const newValue = base + selectedSuggestion.value; const newValue = base + selectedSuggestion.value;
onChangeAndMoveCursor(newValue); buffer.setText(newValue);
onSubmit(newValue); // Execute the command handleSubmitAndClear(newValue);
onChangeAndMoveCursor(''); // Clear query after submit
} else { } else {
// Handle @ command completion
const atIndex = query.lastIndexOf('@'); const atIndex = query.lastIndexOf('@');
if (atIndex === -1) return; if (atIndex === -1) return;
// Find the part of the query after the '@'
const pathPart = query.substring(atIndex + 1); const pathPart = query.substring(atIndex + 1);
// Find the last slash within that part
const lastSlashIndexInPath = pathPart.lastIndexOf('/'); const lastSlashIndexInPath = pathPart.lastIndexOf('/');
let autoCompleteStartIndex = atIndex + 1;
let base = ''; if (lastSlashIndexInPath !== -1) {
if (lastSlashIndexInPath === -1) { autoCompleteStartIndex += lastSlashIndexInPath + 1;
// No slash after '@', replace everything after '@'
base = query.substring(0, atIndex + 1);
} else {
// Slash found, keep everything up to and including the last slash
base = query.substring(0, atIndex + 1 + lastSlashIndexInPath + 1);
} }
buffer.replaceRangeByOffset(
const newValue = base + selectedSuggestion.value; autoCompleteStartIndex,
onChangeAndMoveCursor(newValue); buffer.text.length,
selectedSuggestion.value,
);
} }
resetCompletionState();
resetCompletion(); // Hide suggestions after selection
}, },
[query, suggestions, resetCompletion, onChangeAndMoveCursor, onSubmit], [resetCompletionState, handleSubmitAndClear, buffer, completionSuggestions],
); );
const inputPreprocessor = useCallback( useInput(
(input: string, key: Key) => { (input, key) => {
if (input === '!' && query === '' && !showSuggestions) { if (!focus) {
return;
}
const query = buffer.text;
if (input === '!' && query === '' && !completion.showSuggestions) {
setShellModeActive(!shellModeActive); setShellModeActive(!shellModeActive);
onChangeAndMoveCursor(''); // Clear the '!' from input buffer.setText(''); // Clear the '!' from input
return true; return true;
} }
if (showSuggestions) {
if (completion.showSuggestions) {
if (key.upArrow) { if (key.upArrow) {
navigateSuggestionUp(); completion.navigateUp();
return true; return;
} else if (key.downArrow) { }
navigateSuggestionDown(); if (key.downArrow) {
return true; completion.navigateDown();
} else if (key.tab) { return;
if (suggestions.length > 0) { }
if (key.tab) {
if (completion.suggestions.length > 0) {
const targetIndex = const targetIndex =
activeSuggestionIndex === -1 ? 0 : activeSuggestionIndex; completion.activeSuggestionIndex === -1
if (targetIndex < suggestions.length) { ? 0
: completion.activeSuggestionIndex;
if (targetIndex < completion.suggestions.length) {
handleAutocomplete(targetIndex); handleAutocomplete(targetIndex);
return true;
} }
} }
} else if (key.return) { return;
if (activeSuggestionIndex >= 0) { }
handleAutocomplete(activeSuggestionIndex); if (key.return) {
} else { if (completion.activeSuggestionIndex >= 0) {
if (query.trim()) { handleAutocomplete(completion.activeSuggestionIndex);
handleSubmit(query); } else if (query.trim()) {
} handleSubmitAndClear(query);
} }
return true; return;
} else if (key.escape) {
resetCompletion();
return true;
} }
} else { } else {
// Keybindings when suggestions are not shown // Keybindings when suggestions are not shown
@ -161,60 +188,197 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
inputHistory.navigateDown(); inputHistory.navigateDown();
return true; return true;
} }
if (key.escape) {
completion.resetCompletionState();
return;
}
} }
return false;
// 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,
}, },
[
handleAutocomplete,
navigateSuggestionDown,
navigateSuggestionUp,
query,
suggestions,
showSuggestions,
resetCompletion,
activeSuggestionIndex,
handleSubmit,
inputHistory,
onClearScreen,
shellModeActive,
setShellModeActive,
onChangeAndMoveCursor,
],
); );
const linesToRender = buffer.viewportVisualLines;
const [cursorVisualRowAbsolute, cursorVisualColAbsolute] =
buffer.visualCursor;
const scrollVisualRow = buffer.visualScrollRow;
return ( return (
<Box <>
borderStyle="round" <Box
borderColor={shellModeActive ? Colors.AccentYellow : Colors.AccentBlue} borderStyle="round"
paddingX={1} borderColor={shellModeActive ? Colors.AccentYellow : Colors.AccentBlue}
> paddingX={1}
<Text color={shellModeActive ? Colors.AccentYellow : Colors.AccentPurple}> >
{shellModeActive ? '! ' : '> '} <Text
</Text> color={shellModeActive ? Colors.AccentYellow : Colors.AccentPurple}
<Box flexGrow={1}> >
<MultilineTextEditor {shellModeActive ? '! ' : '> '}
key={editorState.key.toString()} </Text>
initialCursorOffset={editorState.initialCursorOffset} <Box flexGrow={1} flexDirection="column">
initialText={query} {buffer.text.length === 0 && placeholder ? (
onChange={onChange} <Text color={Colors.SubtleComment}>{placeholder}</Text>
placeholder="Type your message or @path/to/file" ) : (
/* Account for width used by the box and &gt; */ linesToRender.map((lineText, visualIdxInRenderedSet) => {
navigateUp={inputHistory.navigateUp} const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
navigateDown={inputHistory.navigateDown} let display = cpSlice(lineText, 0, effectiveWidth);
inputPreprocessor={inputPreprocessor} const currentVisualWidth = stringWidth(display);
widthUsedByParent={3} if (currentVisualWidth < effectiveWidth) {
widthFraction={0.9} display =
onSubmit={() => { display + ' '.repeat(effectiveWidth - currentVisualWidth);
// This onSubmit is for the TextInput component itself. }
// It should only fire if suggestions are NOT showing,
// as inputPreprocessor handles Enter when suggestions are visible. if (visualIdxInRenderedSet === cursorVisualRow) {
const trimmedQuery = query.trim(); const relativeVisualColForHighlight = cursorVisualColAbsolute;
if (!showSuggestions && trimmedQuery) { if (relativeVisualColForHighlight >= 0) {
handleSubmit(trimmedQuery); 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> </Box>
</Box> {completion.showSuggestions && (
<Box>
<SuggestionsDisplay
suggestions={completion.suggestions}
activeIndex={completion.activeSuggestionIndex}
isLoading={completion.isLoadingSuggestions}
width={suggestionsWidth}
scrollOffset={completion.visibleStartIndex}
userInput={buffer.text}
/>
</Box>
)}
</>
); );
}; };

View File

@ -21,15 +21,12 @@ interface ThemeDialogProps {
onHighlight: (themeName: string | undefined) => void; onHighlight: (themeName: string | undefined) => void;
/** The settings object */ /** The settings object */
settings: LoadedSettings; settings: LoadedSettings;
/** Callback to set the query */
setQuery: (query: string) => void;
} }
export function ThemeDialog({ export function ThemeDialog({
onSelect, onSelect,
onHighlight, onHighlight,
settings, settings,
setQuery,
}: ThemeDialogProps): React.JSX.Element { }: ThemeDialogProps): React.JSX.Element {
const [selectedScope, setSelectedScope] = useState<SettingScope>( const [selectedScope, setSelectedScope] = useState<SettingScope>(
SettingScope.User, SettingScope.User,
@ -59,7 +56,6 @@ export function ThemeDialog({
]; ];
const handleThemeSelect = (themeName: string) => { const handleThemeSelect = (themeName: string) => {
setQuery(''); // Clear the query when user selects a theme
onSelect(themeName, selectedScope); onSelect(themeName, selectedScope);
}; };
@ -82,7 +78,6 @@ export function ThemeDialog({
setFocusedSection((prev) => (prev === 'theme' ? 'scope' : 'theme')); setFocusedSection((prev) => (prev === 'theme' ? 'scope' : 'theme'));
} }
if (key.escape) { if (key.escape) {
setQuery(''); // Clear the query when user hits escape
onSelect(undefined, selectedScope); onSelect(undefined, selectedScope);
} }
}); });

View File

@ -1,249 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { useTextBuffer, cpSlice, cpLen } from './text-buffer.js';
import chalk from 'chalk';
import { Box, Text, useInput, useStdin, Key } from 'ink';
import React from 'react';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import { Colors } from '../../colors.js';
import stringWidth from 'string-width';
export interface MultilineTextEditorProps {
// Initial contents.
readonly initialText?: string;
// Placeholder text.
readonly placeholder?: string;
// Visible width.
readonly width?: number;
// Visible height.
readonly height?: number;
// Called when the user submits (plain <Enter> key).
readonly onSubmit?: (text: string) => void;
// Capture keyboard input.
readonly focus?: boolean;
// Called when the internal text buffer updates.
readonly onChange?: (text: string) => void;
// Called when the user attempts to navigate past the start of the editor
// with the up arrow.
readonly navigateUp?: () => void;
// Called when the user attempts to navigate past the end of the editor
// with the down arrow.
readonly navigateDown?: () => void;
// Called on all key events to allow the caller. Returns true if the
// event was handled and should not be passed to the editor.
readonly inputPreprocessor?: (input: string, key: Key) => boolean;
// Optional initial cursor position (character offset)
readonly initialCursorOffset?: number;
readonly widthUsedByParent: number;
readonly widthFraction?: number;
}
export const MultilineTextEditor = ({
initialText = '',
placeholder = '',
width,
height = 10,
onSubmit,
focus = true,
onChange,
initialCursorOffset,
widthUsedByParent,
widthFraction = 1,
navigateUp,
navigateDown,
inputPreprocessor,
}: MultilineTextEditorProps): React.ReactElement => {
const terminalSize = useTerminalSize();
const effectiveWidth = Math.max(
20,
width ??
Math.round(terminalSize.columns * widthFraction) - widthUsedByParent,
);
const { stdin, setRawMode } = useStdin();
const buffer = useTextBuffer({
initialText,
initialCursorOffset,
viewport: { height, width: effectiveWidth },
stdin,
setRawMode,
onChange, // Pass onChange to the hook
});
useInput(
(input, key) => {
if (!focus) {
return;
}
if (inputPreprocessor?.(input, key) === true) {
return;
}
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';
if (isCtrlX) {
buffer.openInExternalEditor();
return;
}
if (
process.env['TEXTBUFFER_DEBUG'] === '1' ||
process.env['TEXTBUFFER_DEBUG'] === 'true'
) {
console.log('[MultilineTextEditor] event', { input, key });
}
if (input.startsWith('[') && input.endsWith('u')) {
const m = input.match(/^\[([0-9]+);([0-9]+)u$/);
if (m && m[1] === '13') {
const mod = Number(m[2]);
const hasCtrl = Math.floor(mod / 4) % 2 === 1;
if (hasCtrl) {
if (onSubmit) {
onSubmit(buffer.text);
}
} else {
buffer.newline();
}
return;
}
}
if (input.startsWith('[27;') && input.endsWith('~')) {
const m = input.match(/^\[27;([0-9]+);13~$/);
if (m) {
const mod = Number(m[1]);
const hasCtrl = Math.floor(mod / 4) % 2 === 1;
if (hasCtrl) {
if (onSubmit) {
onSubmit(buffer.text);
}
} else {
buffer.newline();
}
return;
}
}
if (input === '\n') {
buffer.newline();
return;
}
if (input === '\r') {
if (onSubmit) {
onSubmit(buffer.text);
}
return;
}
if (key.upArrow) {
if (
buffer.visualCursor[0] === 0 &&
buffer.visualScrollRow === 0 &&
navigateUp
) {
navigateUp();
return;
}
}
if (key.downArrow) {
if (
buffer.visualCursor[0] === buffer.allVisualLines.length - 1 &&
navigateDown
) {
navigateDown();
return;
}
}
buffer.handleInput(input, key as Record<string, boolean>);
},
{ isActive: focus },
);
const linesToRender = buffer.viewportVisualLines; // This is the subset of visual lines for display
const [cursorVisualRowAbsolute, cursorVisualColAbsolute] =
buffer.visualCursor; // This is relative to *all* visual lines
const scrollVisualRow = buffer.visualScrollRow;
// scrollHorizontalCol removed as it's always 0 due to word wrap
return (
<Box flexDirection="column">
{buffer.text.length === 0 && placeholder ? (
<Text color={Colors.SubtleComment}>{placeholder}</Text>
) : (
linesToRender.map((lineText, visualIdxInRenderedSet) => {
// cursorVisualRow is the cursor's row index within the currently *rendered* set of visual lines
const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
let display = cpSlice(
lineText,
0, // Start from 0 as horizontal scroll is disabled
effectiveWidth, // This is still code point based for slicing
);
// Pad based on visual width
const currentVisualWidth = stringWidth(display);
if (currentVisualWidth < effectiveWidth) {
display = display + ' '.repeat(effectiveWidth - currentVisualWidth);
}
if (visualIdxInRenderedSet === cursorVisualRow) {
const relativeVisualColForHighlight = cursorVisualColAbsolute; // Directly use absolute as horizontal scroll is 0
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={visualIdxInRenderedSet}>{display}</Text>;
})
)}
</Box>
);
};

View File

@ -6,7 +6,12 @@
import { describe, it, expect, beforeEach } from 'vitest'; import { describe, it, expect, beforeEach } from 'vitest';
import { renderHook, act } from '@testing-library/react'; import { renderHook, act } from '@testing-library/react';
import { useTextBuffer, Viewport, TextBuffer } from './text-buffer.js'; import {
useTextBuffer,
Viewport,
TextBuffer,
offsetToLogicalPos,
} from './text-buffer.js';
// Helper to get the state from the hook // Helper to get the state from the hook
const getBufferState = (result: { current: TextBuffer }) => ({ const getBufferState = (result: { current: TextBuffer }) => ({
@ -512,4 +517,200 @@ describe('useTextBuffer', () => {
// - Selection and clipboard (copy/paste) - might need clipboard API mocks or internal state check // - Selection and clipboard (copy/paste) - might need clipboard API mocks or internal state check
// - openInExternalEditor (heavy mocking of fs, child_process, os) // - openInExternalEditor (heavy mocking of fs, child_process, os)
// - All edge cases for visual scrolling and wrapping with different viewport sizes and text content. // - All edge cases for visual scrolling and wrapping with different viewport sizes and text content.
describe('replaceRange', () => {
it('should replace a single-line range with single-line text', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: '@pac', viewport }),
);
act(() => result.current.replaceRange(0, 1, 0, 4, 'packages'));
const state = getBufferState(result);
expect(state.text).toBe('@packages');
expect(state.cursor).toEqual([0, 9]); // cursor after 'typescript'
});
it('should replace a multi-line range with single-line text', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'hello\nworld\nagain', viewport }),
);
act(() => result.current.replaceRange(0, 2, 1, 3, ' new ')); // replace 'llo\nwor' with ' new '
const state = getBufferState(result);
expect(state.text).toBe('he new ld\nagain');
expect(state.cursor).toEqual([0, 7]); // cursor after ' new '
});
it('should delete a range when replacing with an empty string', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'hello world', viewport }),
);
act(() => result.current.replaceRange(0, 5, 0, 11, '')); // delete ' world'
const state = getBufferState(result);
expect(state.text).toBe('hello');
expect(state.cursor).toEqual([0, 5]);
});
it('should handle replacing at the beginning of the text', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'world', viewport }),
);
act(() => result.current.replaceRange(0, 0, 0, 0, 'hello '));
const state = getBufferState(result);
expect(state.text).toBe('hello world');
expect(state.cursor).toEqual([0, 6]);
});
it('should handle replacing at the end of the text', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'hello', viewport }),
);
act(() => result.current.replaceRange(0, 5, 0, 5, ' world'));
const state = getBufferState(result);
expect(state.text).toBe('hello world');
expect(state.cursor).toEqual([0, 11]);
});
it('should handle replacing the entire buffer content', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'old text', viewport }),
);
act(() => result.current.replaceRange(0, 0, 0, 8, 'new text'));
const state = getBufferState(result);
expect(state.text).toBe('new text');
expect(state.cursor).toEqual([0, 8]);
});
it('should correctly replace with unicode characters', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'hello *** world', viewport }),
);
act(() => result.current.replaceRange(0, 6, 0, 9, '你好'));
const state = getBufferState(result);
expect(state.text).toBe('hello 你好 world');
expect(state.cursor).toEqual([0, 8]); // after '你好'
});
it('should handle invalid range by returning false and not changing text', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'test', viewport }),
);
let success = true;
act(() => {
success = result.current.replaceRange(0, 5, 0, 3, 'fail'); // startCol > endCol in same line
});
expect(success).toBe(false);
expect(getBufferState(result).text).toBe('test');
act(() => {
success = result.current.replaceRange(1, 0, 0, 0, 'fail'); // startRow > endRow
});
expect(success).toBe(false);
expect(getBufferState(result).text).toBe('test');
});
it('replaceRange: multiple lines with a single character', () => {
const { result } = renderHook(() =>
useTextBuffer({ initialText: 'first\nsecond\nthird', viewport }),
);
act(() => result.current.replaceRange(0, 2, 2, 3, 'X')); // Replace 'rst\nsecond\nthi'
const state = getBufferState(result);
expect(state.text).toBe('fiXrd');
expect(state.cursor).toEqual([0, 3]); // After 'X'
});
});
});
describe('offsetToLogicalPos', () => {
it('should return [0,0] for offset 0', () => {
expect(offsetToLogicalPos('any text', 0)).toEqual([0, 0]);
});
it('should handle single line text', () => {
const text = 'hello';
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // Middle 'l'
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End
expect(offsetToLogicalPos(text, 10)).toEqual([0, 5]); // Beyond end
});
it('should handle multi-line text', () => {
const text = 'hello\nworld\n123';
// "hello" (5) + \n (1) + "world" (5) + \n (1) + "123" (3)
// h e l l o \n w o r l d \n 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
// Line 0: "hello" (length 5)
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of 'hello'
expect(offsetToLogicalPos(text, 3)).toEqual([0, 3]); // 'l' in 'hello'
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End of 'hello' (before \n)
// Line 1: "world" (length 5)
expect(offsetToLogicalPos(text, 6)).toEqual([1, 0]); // Start of 'world' (after \n)
expect(offsetToLogicalPos(text, 8)).toEqual([1, 2]); // 'r' in 'world'
expect(offsetToLogicalPos(text, 11)).toEqual([1, 5]); // End of 'world' (before \n)
// Line 2: "123" (length 3)
expect(offsetToLogicalPos(text, 12)).toEqual([2, 0]); // Start of '123' (after \n)
expect(offsetToLogicalPos(text, 13)).toEqual([2, 1]); // '2' in '123'
expect(offsetToLogicalPos(text, 15)).toEqual([2, 3]); // End of '123'
expect(offsetToLogicalPos(text, 20)).toEqual([2, 3]); // Beyond end of text
});
it('should handle empty lines', () => {
const text = 'a\n\nc'; // "a" (1) + \n (1) + "" (0) + \n (1) + "c" (1)
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // 'a'
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // End of 'a'
expect(offsetToLogicalPos(text, 2)).toEqual([1, 0]); // Start of empty line
expect(offsetToLogicalPos(text, 3)).toEqual([2, 0]); // Start of 'c'
expect(offsetToLogicalPos(text, 4)).toEqual([2, 1]); // End of 'c'
});
it('should handle text ending with a newline', () => {
const text = 'hello\n'; // "hello" (5) + \n (1)
expect(offsetToLogicalPos(text, 5)).toEqual([0, 5]); // End of 'hello'
expect(offsetToLogicalPos(text, 6)).toEqual([1, 0]); // Position on the new empty line after
expect(offsetToLogicalPos(text, 7)).toEqual([1, 0]); // Still on the new empty line
});
it('should handle text starting with a newline', () => {
const text = '\nhello'; // "" (0) + \n (1) + "hello" (5)
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of first empty line
expect(offsetToLogicalPos(text, 1)).toEqual([1, 0]); // Start of 'hello'
expect(offsetToLogicalPos(text, 3)).toEqual([1, 2]); // 'l' in 'hello'
});
it('should handle empty string input', () => {
expect(offsetToLogicalPos('', 0)).toEqual([0, 0]);
expect(offsetToLogicalPos('', 5)).toEqual([0, 0]);
});
it('should handle multi-byte unicode characters correctly', () => {
const text = '你好\n世界'; // "你好" (2 chars) + \n (1) + "世界" (2 chars)
// Total "code points" for offset calculation: 2 + 1 + 2 = 5
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]); // Start of '你好'
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // After '你', before '好'
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // End of '你好'
expect(offsetToLogicalPos(text, 3)).toEqual([1, 0]); // Start of '世界'
expect(offsetToLogicalPos(text, 4)).toEqual([1, 1]); // After '世', before '界'
expect(offsetToLogicalPos(text, 5)).toEqual([1, 2]); // End of '世界'
expect(offsetToLogicalPos(text, 6)).toEqual([1, 2]); // Beyond end
});
it('should handle offset exactly at newline character', () => {
const text = 'abc\ndef';
// a b c \n d e f
// 0 1 2 3 4 5 6
expect(offsetToLogicalPos(text, 3)).toEqual([0, 3]); // End of 'abc'
// The next character is the newline, so an offset of 4 means the start of the next line.
expect(offsetToLogicalPos(text, 4)).toEqual([1, 0]); // Start of 'def'
});
it('should handle offset in the middle of a multi-byte character (should place at start of that char)', () => {
// This scenario is tricky as "offset" is usually character-based.
// Assuming cpLen and related logic handles this by treating multi-byte as one unit.
// The current implementation of offsetToLogicalPos uses cpLen, so it should be code-point aware.
const text = '🐶🐱'; // 2 code points
expect(offsetToLogicalPos(text, 0)).toEqual([0, 0]);
expect(offsetToLogicalPos(text, 1)).toEqual([0, 1]); // After 🐶
expect(offsetToLogicalPos(text, 2)).toEqual([0, 2]); // After 🐱
});
}); });

View File

@ -119,6 +119,56 @@ function calculateInitialCursorPosition(
} }
return [0, 0]; // Default for empty text return [0, 0]; // Default for empty text
} }
export function offsetToLogicalPos(
text: string,
offset: number,
): [number, number] {
let row = 0;
let col = 0;
let currentOffset = 0;
if (offset === 0) return [0, 0];
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineLength = cpLen(line);
const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
if (offset <= currentOffset + lineLength) {
// Check against lineLength first
row = i;
col = offset - currentOffset;
return [row, col];
} else if (offset <= currentOffset + lineLengthWithNewline) {
// Check if offset is the newline itself
row = i;
col = lineLength; // Position cursor at the end of the current line content
// If the offset IS the newline, and it's not the last line, advance to next line, col 0
if (
offset === currentOffset + lineLengthWithNewline &&
i < lines.length - 1
) {
return [i + 1, 0];
}
return [row, col]; // Otherwise, it's at the end of the current line content
}
currentOffset += lineLengthWithNewline;
}
// If offset is beyond the text length, place cursor at the end of the last line
// or [0,0] if text is empty
if (lines.length > 0) {
row = lines.length - 1;
col = cpLen(lines[row]);
} else {
row = 0;
col = 0;
}
return [row, col];
}
// Helper to calculate visual lines and map cursor positions // Helper to calculate visual lines and map cursor positions
function calculateVisualLayout( function calculateVisualLayout(
logicalLines: string[], logicalLines: string[],
@ -1178,6 +1228,31 @@ export function useTextBuffer({
[visualLines, visualScrollRow, viewport.height], [visualLines, visualScrollRow, viewport.height],
); );
const replaceRangeByOffset = useCallback(
(
startOffset: number,
endOffset: number,
replacementText: string,
): boolean => {
dbg('replaceRangeByOffset', { startOffset, endOffset, replacementText });
const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
return replaceRange(startRow, startCol, endRow, endCol, replacementText);
},
[text, replaceRange],
);
const moveToOffset = useCallback(
(offset: number): void => {
const [newRow, newCol] = offsetToLogicalPos(text, offset);
setCursorRow(newRow);
setCursorCol(newCol);
setPreferredCol(null);
dbg('moveToOffset', { offset, newCursor: [newRow, newCol] });
},
[text, setPreferredCol],
);
const returnValue: TextBuffer = { const returnValue: TextBuffer = {
lines, lines,
text, text,
@ -1199,6 +1274,8 @@ export function useTextBuffer({
undo, undo,
redo, redo,
replaceRange, replaceRange,
replaceRangeByOffset,
moveToOffset, // Added here
deleteWordLeft, deleteWordLeft,
deleteWordRight, deleteWordRight,
killLineRight, killLineRight,
@ -1342,4 +1419,10 @@ export interface TextBuffer {
copy: () => string | null; copy: () => string | null;
paste: () => boolean; paste: () => boolean;
startSelection: () => void; startSelection: () => void;
replaceRangeByOffset: (
startOffset: number,
endOffset: number,
replacementText: string,
) => boolean;
moveToOffset(offset: number): void;
} }