summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/components/shared
diff options
context:
space:
mode:
Diffstat (limited to 'packages/cli/src/ui/components/shared')
-rw-r--r--packages/cli/src/ui/components/shared/multiline-editor.tsx249
-rw-r--r--packages/cli/src/ui/components/shared/text-buffer.test.ts203
-rw-r--r--packages/cli/src/ui/components/shared/text-buffer.ts83
3 files changed, 285 insertions, 250 deletions
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 <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>
- );
-};
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;
}