diff --git a/packages/cli/src/ui/App.tsx b/packages/cli/src/ui/App.tsx index d168e0e6..7f16f4e5 100644 --- a/packages/cli/src/ui/App.tsx +++ b/packages/cli/src/ui/App.tsx @@ -17,7 +17,7 @@ import { Header } from './components/Header.js'; import { LoadingIndicator } from './components/LoadingIndicator.js'; import { AutoAcceptIndicator } from './components/AutoAcceptIndicator.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 { ThemeDialog } from './components/ThemeDialog.js'; import { type Config } from '@gemini-code/server'; @@ -28,9 +28,6 @@ import { LoadedSettings } from '../config/settings.js'; import { Tips } from './components/Tips.js'; import { ConsoleOutput } from './components/ConsolePatcher.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 process from 'node:process'; // For performMemoryRefresh import { MessageType } from './types.js'; // For performMemoryRefresh @@ -99,7 +96,6 @@ export const App = ({ config.setGeminiMdFileCount(fileCount); setGeminiMdFileCount(fileCount); - // chatSessionRef.current = null; // This was in useGeminiStream, might need similar logic or pass chat ref addItem( { type: MessageType.INFO, @@ -126,7 +122,7 @@ export const App = ({ }, [config, addItem]); const { handleSlashCommand, slashCommands } = useSlashCommandProcessor( - config, // Pass config + config, addItem, clearItems, refreshStatic, @@ -176,53 +172,24 @@ export const App = ({ const isInputActive = streamingState === StreamingState.Idle && !initError; - const [query, setQuery] = useState(''); - const [editorState, setEditorState] = useState({ - 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(() => { clearItems(); console.clear(); refreshStatic(); }, [clearItems, refreshStatic]); - const completion = useCompletion( - query, - config.getTargetDir(), - !shellModeActive && - isInputActive && - (isAtCommand(query) || isSlashCommand(query)), - slashCommands, - ); - // --- Render Logic --- - const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize(); + const { rows: terminalHeight } = useTerminalSize(); const mainControlsRef = useRef(null); const pendingHistoryItemRef = useRef(null); - // Calculate width for suggestions, leave some padding - const suggestionsWidth = Math.max(60, Math.floor(terminalWidth * 0.8)); - useEffect(() => { if (mainControlsRef.current) { const fullFooterMeasurement = measureElement(mainControlsRef.current); setFooterHeight(fullFooterMeasurement.height); } - }, [terminalHeight]); // Re-calculate if terminalHeight changes, as it might affect footer's rendered height. + }, [terminalHeight]); const availableTerminalHeight = useMemo(() => { const staticExtraHeight = /* margins and padding */ 3; @@ -326,7 +293,6 @@ export const App = ({ onSelect={handleThemeSelect} onHighlight={handleThemeHighlight} settings={settings} - setQuery={setQuery} /> ) : ( @@ -361,37 +327,16 @@ export const App = ({ {isInputActive && ( - <> - - {completion.showSuggestions && !shellModeActive && ( - - - - )} - + )} )} diff --git a/packages/cli/src/ui/components/InputPrompt.tsx b/packages/cli/src/ui/components/InputPrompt.tsx index 38af2a8c..26c9d14f 100644 --- a/packages/cli/src/ui/components/InputPrompt.tsx +++ b/packages/cli/src/ui/components/InputPrompt.tsx @@ -5,147 +5,174 @@ */ import React, { useCallback } from 'react'; -import { Text, Box, Key } from 'ink'; +import { Text, Box, useInput, useStdin } from 'ink'; import { Colors } from '../colors.js'; -import { Suggestion } from './SuggestionsDisplay.js'; -import { MultilineTextEditor } from './shared/multiline-editor.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 { - query: string; - onChange: (value: string) => void; - onChangeAndMoveCursor: (value: string) => void; - editorState: EditorState; onSubmit: (value: string) => void; - showSuggestions: boolean; - suggestions: Suggestion[]; - activeSuggestionIndex: number; - resetCompletion: () => void; userMessages: readonly string[]; - navigateSuggestionUp: () => void; - navigateSuggestionDown: () => 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; setShellModeActive: (value: boolean) => void; } -export interface EditorState { - key: number; - initialCursorOffset?: number; -} - export const InputPrompt: React.FC = ({ - query, - onChange, - onChangeAndMoveCursor, - editorState, onSubmit, - showSuggestions, - suggestions, - activeSuggestionIndex, userMessages, - navigateSuggestionUp, - navigateSuggestionDown, - resetCompletion, onClearScreen, + config, + slashCommands, + placeholder = 'Enter your message or use tools (e.g., @src/file.txt)...', + height = 10, + focus = true, + widthFraction, shellModeActive, 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) => { 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({ userMessages, - onSubmit: handleSubmit, - isActive: !showSuggestions, // Input history is active when suggestions are not shown - currentQuery: query, + onSubmit: handleSubmitAndClear, + isActive: !completion.showSuggestions, + currentQuery: buffer.text, onChangeAndMoveCursor, }); + const completionSuggestions = completion.suggestions; const handleAutocomplete = useCallback( (indexToUse: number) => { - if (indexToUse < 0 || indexToUse >= suggestions.length) { + if (indexToUse < 0 || indexToUse >= completionSuggestions.length) { return; } - const selectedSuggestion = suggestions[indexToUse]; - const trimmedQuery = query.trimStart(); + const query = buffer.text; + const selectedSuggestion = completionSuggestions[indexToUse]; - if (trimmedQuery.startsWith('/')) { - // Handle / command completion + if (query.trimStart().startsWith('/')) { const slashIndex = query.indexOf('/'); const base = query.substring(0, slashIndex + 1); const newValue = base + selectedSuggestion.value; - onChangeAndMoveCursor(newValue); - onSubmit(newValue); // Execute the command - onChangeAndMoveCursor(''); // Clear query after submit + buffer.setText(newValue); + handleSubmitAndClear(newValue); } else { - // Handle @ command completion const atIndex = query.lastIndexOf('@'); if (atIndex === -1) return; - - // Find the part of the query after the '@' const pathPart = query.substring(atIndex + 1); - // Find the last slash within that part const lastSlashIndexInPath = pathPart.lastIndexOf('/'); - - let base = ''; - if (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); + let autoCompleteStartIndex = atIndex + 1; + if (lastSlashIndexInPath !== -1) { + autoCompleteStartIndex += lastSlashIndexInPath + 1; } - - const newValue = base + selectedSuggestion.value; - onChangeAndMoveCursor(newValue); + buffer.replaceRangeByOffset( + autoCompleteStartIndex, + buffer.text.length, + selectedSuggestion.value, + ); } - - resetCompletion(); // Hide suggestions after selection + resetCompletionState(); }, - [query, suggestions, resetCompletion, onChangeAndMoveCursor, onSubmit], + [resetCompletionState, handleSubmitAndClear, buffer, completionSuggestions], ); - const inputPreprocessor = useCallback( - (input: string, key: Key) => { - if (input === '!' && query === '' && !showSuggestions) { + useInput( + (input, key) => { + if (!focus) { + return; + } + const query = buffer.text; + + if (input === '!' && query === '' && !completion.showSuggestions) { setShellModeActive(!shellModeActive); - onChangeAndMoveCursor(''); // Clear the '!' from input + buffer.setText(''); // Clear the '!' from input return true; } - if (showSuggestions) { + + if (completion.showSuggestions) { if (key.upArrow) { - navigateSuggestionUp(); - return true; - } else if (key.downArrow) { - navigateSuggestionDown(); - return true; - } else if (key.tab) { - if (suggestions.length > 0) { + completion.navigateUp(); + return; + } + if (key.downArrow) { + completion.navigateDown(); + return; + } + if (key.tab) { + if (completion.suggestions.length > 0) { const targetIndex = - activeSuggestionIndex === -1 ? 0 : activeSuggestionIndex; - if (targetIndex < suggestions.length) { + completion.activeSuggestionIndex === -1 + ? 0 + : completion.activeSuggestionIndex; + if (targetIndex < completion.suggestions.length) { handleAutocomplete(targetIndex); - return true; } } - } else if (key.return) { - if (activeSuggestionIndex >= 0) { - handleAutocomplete(activeSuggestionIndex); - } else { - if (query.trim()) { - handleSubmit(query); - } + return; + } + if (key.return) { + if (completion.activeSuggestionIndex >= 0) { + handleAutocomplete(completion.activeSuggestionIndex); + } else if (query.trim()) { + handleSubmitAndClear(query); } - return true; - } else if (key.escape) { - resetCompletion(); - return true; + return; } } else { // Keybindings when suggestions are not shown @@ -161,60 +188,197 @@ export const InputPrompt: React.FC = ({ inputHistory.navigateDown(); 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); + }, + { + 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 ( - - - {shellModeActive ? '! ' : '> '} - - - { - // 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. - const trimmedQuery = query.trim(); - if (!showSuggestions && trimmedQuery) { - handleSubmit(trimmedQuery); - } - }} - /> + <> + + + {shellModeActive ? '! ' : '> '} + + + {buffer.text.length === 0 && placeholder ? ( + {placeholder} + ) : ( + 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 ( + {display} + ); + }) + )} + - + {completion.showSuggestions && ( + + + + )} + ); }; diff --git a/packages/cli/src/ui/components/ThemeDialog.tsx b/packages/cli/src/ui/components/ThemeDialog.tsx index 7ab4e3b1..58bfeffa 100644 --- a/packages/cli/src/ui/components/ThemeDialog.tsx +++ b/packages/cli/src/ui/components/ThemeDialog.tsx @@ -21,15 +21,12 @@ interface ThemeDialogProps { onHighlight: (themeName: string | undefined) => void; /** The settings object */ settings: LoadedSettings; - /** Callback to set the query */ - setQuery: (query: string) => void; } export function ThemeDialog({ onSelect, onHighlight, settings, - setQuery, }: ThemeDialogProps): React.JSX.Element { const [selectedScope, setSelectedScope] = useState( SettingScope.User, @@ -59,7 +56,6 @@ export function ThemeDialog({ ]; const handleThemeSelect = (themeName: string) => { - setQuery(''); // Clear the query when user selects a theme onSelect(themeName, selectedScope); }; @@ -82,7 +78,6 @@ export function ThemeDialog({ setFocusedSection((prev) => (prev === 'theme' ? 'scope' : 'theme')); } if (key.escape) { - setQuery(''); // Clear the query when user hits escape onSelect(undefined, selectedScope); } }); diff --git a/packages/cli/src/ui/components/shared/multiline-editor.tsx b/packages/cli/src/ui/components/shared/multiline-editor.tsx deleted file mode 100644 index 890a9b47..00000000 --- a/packages/cli/src/ui/components/shared/multiline-editor.tsx +++ /dev/null @@ -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 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); - }, - { 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 ( - - {buffer.text.length === 0 && placeholder ? ( - {placeholder} - ) : ( - 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 {display}; - }) - )} - - ); -}; diff --git a/packages/cli/src/ui/components/shared/text-buffer.test.ts b/packages/cli/src/ui/components/shared/text-buffer.test.ts index acaa4179..704666d1 100644 --- a/packages/cli/src/ui/components/shared/text-buffer.test.ts +++ b/packages/cli/src/ui/components/shared/text-buffer.test.ts @@ -6,7 +6,12 @@ import { describe, it, expect, beforeEach } from 'vitest'; 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 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 // - openInExternalEditor (heavy mocking of fs, child_process, os) // - 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 🐱 + }); }); diff --git a/packages/cli/src/ui/components/shared/text-buffer.ts b/packages/cli/src/ui/components/shared/text-buffer.ts index f84d83bc..a8b8cef3 100644 --- a/packages/cli/src/ui/components/shared/text-buffer.ts +++ b/packages/cli/src/ui/components/shared/text-buffer.ts @@ -119,6 +119,56 @@ function calculateInitialCursorPosition( } 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 function calculateVisualLayout( logicalLines: string[], @@ -1178,6 +1228,31 @@ export function useTextBuffer({ [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 = { lines, text, @@ -1199,6 +1274,8 @@ export function useTextBuffer({ undo, redo, replaceRange, + replaceRangeByOffset, + moveToOffset, // Added here deleteWordLeft, deleteWordRight, killLineRight, @@ -1342,4 +1419,10 @@ export interface TextBuffer { copy: () => string | null; paste: () => boolean; startSelection: () => void; + replaceRangeByOffset: ( + startOffset: number, + endOffset: number, + replacementText: string, + ) => boolean; + moveToOffset(offset: number): void; }