Skip to main content

infinity_agent_cli/
text_input.rs

1use crate::component::{Component, KeyResult};
2use ratatui::{
3    buffer::Buffer,
4    crossterm::event::{KeyCode, KeyEvent, KeyModifiers},
5    layout::{Position, Rect},
6    style::Color,
7    widgets::Widget,
8};
9use std::cell::Cell;
10use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
11
12const PAD_X: u16 = 1;
13const PAD_Y: u16 = 1;
14const BG: Color = Color::Rgb(40, 40, 40);
15const FG: Color = Color::White;
16
17/// A multi-line text input with its own wrapping, cursor tracking, and rendering.
18pub struct TextInput {
19    buf: String,
20    /// Byte-offset cursor position within `buf`.
21    cursor: usize,
22    /// Last-known inner wrapping width (set during `preferred_height` / `render`).
23    /// Used by `move_up` / `move_down` so they can navigate visual lines without
24    /// needing an explicit width parameter.
25    wrap_width: Cell<u16>,
26}
27
28/// Snapshot returned by `render_state` so the caller can place the terminal cursor.
29pub struct RenderResult {
30    /// Absolute screen position where the blinking cursor should be placed.
31    pub cursor_position: Position,
32}
33
34impl Default for TextInput {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl TextInput {
41    pub fn new() -> Self {
42        Self {
43            buf: String::new(),
44            cursor: 0,
45            wrap_width: Cell::new(0),
46        }
47    }
48
49    // ── Public mutation API ──────────────────────────────────────────
50
51    pub fn insert_char(&mut self, ch: char) {
52        self.buf.insert(self.cursor, ch);
53        self.cursor += ch.len_utf8();
54    }
55
56    /// Insert an arbitrary string at the cursor (e.g. from a bracketed paste).
57    /// The cursor advances to the end of the inserted text.
58    pub fn insert_str(&mut self, s: &str) {
59        self.buf.insert_str(self.cursor, s);
60        self.cursor += s.len();
61    }
62
63    pub fn backspace(&mut self) {
64        if self.cursor > 0 {
65            // Find the previous char boundary
66            let prev = self.buf[..self.cursor]
67                .char_indices()
68                .next_back()
69                .map(|(i, _)| i)
70                .unwrap_or(0);
71            self.buf.drain(prev..self.cursor);
72            self.cursor = prev;
73        }
74    }
75
76    pub fn delete(&mut self) {
77        if self.cursor < self.buf.len() {
78            let next = self.cursor
79                + self.buf[self.cursor..]
80                    .chars()
81                    .next()
82                    .expect("bug: cursor within bounds but no char found")
83                    .len_utf8();
84            self.buf.drain(self.cursor..next);
85        }
86    }
87
88    pub fn move_left(&mut self) {
89        if self.cursor > 0 {
90            self.cursor = self.buf[..self.cursor]
91                .char_indices()
92                .next_back()
93                .map(|(i, _)| i)
94                .unwrap_or(0);
95        }
96    }
97
98    pub fn move_right(&mut self) {
99        if self.cursor < self.buf.len() {
100            self.cursor += self.buf[self.cursor..]
101                .chars()
102                .next()
103                .expect("bug: cursor within bounds but no char found")
104                .len_utf8();
105        }
106    }
107
108    pub fn move_home(&mut self) {
109        self.cursor = 0;
110    }
111
112    pub fn move_end(&mut self) {
113        self.cursor = self.buf.len();
114    }
115
116    /// Move the cursor up one visual (wrapped) line.
117    /// If the cursor is already on the first line, it moves to the beginning.
118    pub fn move_up(&mut self) {
119        let wrap_w = self.wrap_width.get() as usize;
120        if wrap_w == 0 {
121            return;
122        }
123
124        let (row, col) = self.cursor_visual_pos(wrap_w);
125        if row == 0 {
126            self.cursor = 0;
127        } else {
128            self.set_cursor_to_visual_pos(row - 1, col, wrap_w);
129        }
130    }
131
132    /// Move the cursor down one visual (wrapped) line.
133    /// If the cursor is already on the last line, it moves to the end.
134    pub fn move_down(&mut self) {
135        let wrap_w = self.wrap_width.get() as usize;
136        if wrap_w == 0 {
137            return;
138        }
139
140        let (row, col) = self.cursor_visual_pos(wrap_w);
141        let total_rows = self.visual_line_count(wrap_w);
142
143        if row >= total_rows - 1 {
144            self.cursor = self.buf.len();
145        } else {
146            self.set_cursor_to_visual_pos(row + 1, col, wrap_w);
147        }
148    }
149
150    /// Returns `(visual_row, display_column)` for the current cursor position
151    /// given a wrapping width.
152    fn cursor_visual_pos(&self, wrap_w: usize) -> (usize, usize) {
153        let lines = wrap_lines(&self.buf, wrap_w);
154        let buf_start = self.buf.as_ptr() as usize;
155
156        for (row_idx, line) in lines.iter().enumerate() {
157            let line_byte_start = line.as_ptr() as usize - buf_start;
158            let line_byte_end = line_byte_start + line.len();
159
160            if self.cursor >= line_byte_start && self.cursor <= line_byte_end {
161                let offset = self.cursor.saturating_sub(line_byte_start);
162                let col = line[..offset.min(line.len())].width();
163
164                // If the cursor is at the end of a line that fills the full
165                // width, it logically sits at col 0 of the next row (matching
166                // the same logic used in `render`).
167                let line_full = line.width() >= wrap_w;
168                if offset == line.len() && line_full {
169                    continue;
170                }
171
172                return (row_idx, col);
173            }
174        }
175
176        // Fallback: cursor is past all content.
177        if let Some(last) = lines.last() {
178            let last_full = last.width() >= wrap_w;
179            if last_full && self.cursor == self.buf.len() {
180                return (lines.len(), 0);
181            }
182            return (lines.len().saturating_sub(1), last.width());
183        }
184
185        (0, 0)
186    }
187
188    /// Total number of visual rows (at least 1) for the current buffer at the
189    /// given wrapping width, including the potential extra row when the last
190    /// line is exactly full and the cursor sits at the buffer end.
191    fn visual_line_count(&self, wrap_w: usize) -> usize {
192        let lines = wrap_lines(&self.buf, wrap_w);
193        let extra = lines
194            .last()
195            .map(|l| l.width() >= wrap_w && self.cursor == self.buf.len())
196            .unwrap_or(false);
197        lines.len() + extra as usize
198    }
199
200    /// Move the cursor to the given visual `(row, col)`, clamping the column
201    /// to the actual width of the target line.
202    fn set_cursor_to_visual_pos(&mut self, target_row: usize, target_col: usize, wrap_w: usize) {
203        let new_cursor = {
204            let lines = wrap_lines(&self.buf, wrap_w);
205            let buf_start = self.buf.as_ptr() as usize;
206
207            if target_row >= lines.len() {
208                self.buf.len()
209            } else {
210                let line = lines[target_row];
211                let line_byte_start = line.as_ptr() as usize - buf_start;
212
213                // Walk the line accumulating display widths to find the byte
214                // offset corresponding to the target column.
215                let mut byte_offset = line.len();
216                let mut acc = 0;
217                for (i, ch) in line.char_indices() {
218                    if acc >= target_col {
219                        byte_offset = i;
220                        break;
221                    }
222                    acc += ch.width().unwrap_or(0);
223                }
224
225                line_byte_start + byte_offset
226            }
227        };
228        self.cursor = new_cursor;
229    }
230
231    /// Move cursor one word to the left (Option+Left / Ctrl+Left).
232    pub fn move_word_left(&mut self) {
233        // Skip whitespace to the left, then skip non-whitespace.
234        let before = &self.buf[..self.cursor];
235        let trimmed = before.trim_end();
236        if trimmed.is_empty() {
237            self.cursor = 0;
238            return;
239        }
240        // Find the start of the current word
241        if let Some((i, _)) = trimmed
242            .char_indices()
243            .rev()
244            .find(|(_, c)| c.is_whitespace())
245        {
246            // `i` is the byte index of the space; skip past it
247            self.cursor = i + trimmed[i..]
248                .chars()
249                .next()
250                .expect("bug: whitespace char index valid but no char found")
251                .len_utf8();
252        } else {
253            self.cursor = 0;
254        }
255    }
256
257    /// Move cursor one word to the right (Option+Right / Ctrl+Right).
258    pub fn move_word_right(&mut self) {
259        let after = &self.buf[self.cursor..];
260        // Skip non-whitespace, then skip whitespace.
261        let skip_word = after
262            .char_indices()
263            .find(|(_, c)| c.is_whitespace())
264            .map(|(i, _)| i)
265            .unwrap_or(after.len());
266        let rest = &after[skip_word..];
267        let skip_space = rest
268            .char_indices()
269            .find(|(_, c)| !c.is_whitespace())
270            .map(|(i, _)| i)
271            .unwrap_or(rest.len());
272        self.cursor += skip_word + skip_space;
273    }
274
275    /// Delete the word to the left of the cursor (Option+Backspace).
276    pub fn delete_word_left(&mut self) {
277        let start = self.cursor;
278        self.move_word_left();
279        self.buf.drain(self.cursor..start);
280    }
281
282    /// Insert a newline at the cursor (Shift+Enter).
283    pub fn insert_newline(&mut self) {
284        self.insert_char('\n');
285    }
286
287    /// Handle a key event. Returns `KeyResult::Captured` if the event was consumed by the
288    /// input area, `KeyResult::NotCaptured` if it should fall through to other handlers.
289    pub fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
290        let mods = key.modifiers;
291        let ctrl = mods.contains(KeyModifiers::CONTROL);
292        let alt = mods.contains(KeyModifiers::ALT);
293
294        match key.code {
295            // ── Word-level navigation (Option/Alt + arrows) ─────────
296            // On macOS, Option+Left/Right emit Alt+b / Alt+f (escape
297            // sequences \x1bb / \x1bf) rather than Alt+Arrow.
298            KeyCode::Left if alt => {
299                self.move_word_left();
300                KeyResult::Captured
301            }
302            KeyCode::Right if alt => {
303                self.move_word_right();
304                KeyResult::Captured
305            }
306            KeyCode::Char('b') if alt => {
307                self.move_word_left();
308                KeyResult::Captured
309            }
310            KeyCode::Char('f') if alt => {
311                self.move_word_right();
312                KeyResult::Captured
313            }
314
315            // ── Emacs-style line nav ────────────────────────────────
316            KeyCode::Char('a') if ctrl => {
317                self.move_home();
318                KeyResult::Captured
319            }
320            KeyCode::Char('e') if ctrl => {
321                self.move_end();
322                KeyResult::Captured
323            }
324
325            // ── Ctrl+C clears input; falls through if already empty ─
326            KeyCode::Char('c') if ctrl => {
327                if !self.is_empty() {
328                    self.buf.clear();
329                    self.cursor = 0;
330                    KeyResult::Captured
331                } else {
332                    KeyResult::NotCaptured
333                }
334            }
335
336            // ── Ctrl+J → newline (universal alternative to Alt+Enter) ──
337            // macOS Terminal.app uses Option for character composition by
338            // default, so Alt+Enter is not recognized there.
339            KeyCode::Char('j') if ctrl => {
340                self.insert_newline();
341                KeyResult::Captured
342            }
343
344            // ── Let Ctrl+<key> combos we don't handle fall through ──
345            KeyCode::Char(_) if ctrl => KeyResult::NotCaptured,
346
347            // ── Delete word left (Option+Backspace / Alt+Backspace) ──
348            KeyCode::Backspace if alt => {
349                self.delete_word_left();
350                KeyResult::Captured
351            }
352
353            // ── Alt+Enter → newline ──────────────────────────────────
354            KeyCode::Enter if alt => {
355                self.insert_newline();
356                KeyResult::Captured
357            }
358
359            // ── Plain Enter → not ours, let terminal submit ─────────
360            KeyCode::Enter => KeyResult::NotCaptured,
361
362            // ── Basic editing ───────────────────────────────────────
363            KeyCode::Backspace => {
364                self.backspace();
365                KeyResult::Captured
366            }
367            KeyCode::Delete => {
368                self.delete();
369                KeyResult::Captured
370            }
371            KeyCode::Left => {
372                self.move_left();
373                KeyResult::Captured
374            }
375            KeyCode::Right => {
376                self.move_right();
377                KeyResult::Captured
378            }
379            KeyCode::Up => {
380                if self.cursor == 0 {
381                    KeyResult::NotCaptured
382                } else {
383                    self.move_up();
384                    KeyResult::Captured
385                }
386            }
387            KeyCode::Down => {
388                self.move_down();
389                KeyResult::Captured
390            }
391            KeyCode::Home => {
392                self.move_home();
393                KeyResult::Captured
394            }
395            KeyCode::End => {
396                self.move_end();
397                KeyResult::Captured
398            }
399            KeyCode::Char(ch) => {
400                self.insert_char(ch);
401                KeyResult::Captured
402            }
403
404            _ => KeyResult::NotCaptured,
405        }
406    }
407
408    /// Take the current text, clear the buffer, and reset the cursor.
409    pub fn take_text(&mut self) -> String {
410        self.cursor = 0;
411        std::mem::take(&mut self.buf)
412    }
413
414    pub fn text(&self) -> &str {
415        &self.buf
416    }
417
418    pub fn set_text(&mut self, s: &str) {
419        self.buf = s.to_owned();
420        self.cursor = self.buf.len();
421    }
422
423    pub fn is_empty(&self) -> bool {
424        self.buf.trim().is_empty()
425    }
426
427    // ── Layout ──────────────────────────────────────────────────────
428
429    /// The total height this widget wants given a particular outer width.
430    /// Includes top/bottom padding rows.
431    pub fn preferred_height(&self, outer_width: u16) -> u16 {
432        let inner_w = outer_width.saturating_sub(PAD_X * 2);
433        self.wrap_width.set(inner_w);
434        if inner_w == 0 {
435            return PAD_Y * 2 + 1;
436        }
437        let lines = wrap_lines(&self.buf, inner_w as usize);
438        let mut text_rows = lines.len().max(1) as u16;
439
440        // If the cursor sits past a full last line, it will render on an
441        // extra row — make sure we reserve space for it.
442        if let Some(last) = lines.last()
443            && last.width() >= inner_w as usize
444            && self.cursor == self.buf.len()
445        {
446            text_rows += 1;
447        }
448
449        PAD_Y * 2 + text_rows
450    }
451
452    // ── Rendering ───────────────────────────────────────────────────
453
454    /// Render into the given area and return the cursor screen position.
455    pub fn render(&self, area: Rect, buf: &mut Buffer) -> RenderResult {
456        // Fill background
457        for y in area.y..area.bottom() {
458            for x in area.x..area.right() {
459                buf[(x, y)].set_char(' ').set_bg(BG);
460            }
461        }
462
463        let inner = Rect::new(
464            area.x + PAD_X,
465            area.y + PAD_Y,
466            area.width.saturating_sub(PAD_X * 2),
467            area.height.saturating_sub(PAD_Y * 2),
468        );
469
470        self.wrap_width.set(inner.width);
471
472        if inner.width == 0 || inner.height == 0 {
473            return RenderResult {
474                cursor_position: Position::new(area.x + PAD_X, area.y + PAD_Y),
475            };
476        }
477
478        let lines = wrap_lines(&self.buf, inner.width as usize);
479
480        // Find which visual line/col the cursor falls on (col in display
481        // columns, so wide characters count as 2).
482        let mut cursor_row: u16 = 0;
483        let mut cursor_col: u16 = 0;
484        let mut found_cursor = false;
485        let buf_start = self.buf.as_ptr() as usize;
486
487        for (row_idx, line) in lines.iter().enumerate() {
488            let line_byte_start = line.as_ptr() as usize - buf_start;
489            let line_byte_end = line_byte_start + line.len();
490            if !found_cursor && self.cursor >= line_byte_start && self.cursor <= line_byte_end {
491                let offset = self.cursor.saturating_sub(line_byte_start);
492                let col = line[..offset.min(line.len())].width();
493
494                // If the cursor is at the end of a line that is exactly
495                // max_width columns wide, it should appear at column 0 of
496                // the next visual row (like a real text editor).
497                let line_full = line.width() >= inner.width as usize;
498                if offset == line.len() && line_full {
499                    // Let the next iteration (or the fallback below)
500                    // place the cursor on the following row.
501                    continue;
502                }
503
504                cursor_row = row_idx as u16;
505                cursor_col = col as u16;
506                found_cursor = true;
507            }
508        }
509
510        // Cursor is past all wrapped content — place it at col 0 of the
511        // next row (happens when the last line is exactly full) or at the
512        // end of the last line.
513        if !found_cursor && let Some(last) = lines.last() {
514            let last_full = last.width() >= inner.width as usize;
515            if last_full && self.cursor == self.buf.len() {
516                cursor_row = lines.len() as u16;
517                cursor_col = 0;
518            } else {
519                cursor_row = lines.len().saturating_sub(1) as u16;
520                cursor_col = last.width() as u16;
521            }
522        }
523
524        // Draw text, advancing by display width so wide characters occupy
525        // two columns (the cell after a wide char is skipped).
526        for (row_idx, line) in lines.iter().enumerate() {
527            let y = inner.y + row_idx as u16;
528            if y >= inner.bottom() {
529                break;
530            }
531            let mut x = inner.x;
532            for ch in line.chars() {
533                let w = ch.width().unwrap_or(0) as u16;
534                if w == 0 {
535                    continue;
536                }
537                if x + w > inner.right() {
538                    break;
539                }
540                buf[(x, y)].set_char(ch).set_fg(FG).set_bg(BG);
541                x += w;
542            }
543        }
544
545        RenderResult {
546            cursor_position: Position::new(
547                inner.x + cursor_col,
548                (inner.y + cursor_row).min(inner.bottom().saturating_sub(1)),
549            ),
550        }
551    }
552}
553
554/// Word-wrap `text` into lines of at most `max_width` display columns.
555/// Handles explicit newlines and soft-wraps long lines.
556/// Returns a vec of string slices (borrowed from `text`).
557fn wrap_lines<'a>(text: &'a str, max_width: usize) -> Vec<&'a str> {
558    if text.is_empty() {
559        // Return a slice of `text` (not a string literal) so pointer
560        // arithmetic in the caller stays valid.
561        return vec![&text[..0]];
562    }
563    if max_width == 0 {
564        return vec![text];
565    }
566
567    let mut lines: Vec<&'a str> = Vec::new();
568
569    // First split on hard newlines, then soft-wrap each segment.
570    for segment in text.split('\n') {
571        // For empty segments (consecutive newlines), push an empty slice
572        // that still points into `text` so pointer arithmetic works.
573        if segment.is_empty() {
574            // Use the byte position of this segment within text.
575            let offset = segment.as_ptr() as usize - text.as_ptr() as usize;
576            lines.push(&text[offset..offset]);
577            continue;
578        }
579
580        let mut remaining = segment;
581        while !remaining.is_empty() {
582            if remaining.width() <= max_width {
583                lines.push(remaining);
584                break;
585            }
586
587            // Find the byte index where the accumulated display width
588            // would exceed max_width.
589            let mut break_byte = remaining.len();
590            let mut acc = 0;
591            for (i, ch) in remaining.char_indices() {
592                let w = ch.width().unwrap_or(0);
593                if acc + w > max_width {
594                    break_byte = i;
595                    break;
596                }
597                acc += w;
598            }
599            // Guard against a single char wider than the wrap width.
600            if break_byte == 0 {
601                break_byte = remaining
602                    .chars()
603                    .next()
604                    .expect("bug: remaining is non-empty")
605                    .len_utf8();
606            }
607
608            // Try to break at the last space within the first max_width columns
609            let seg = &remaining[..break_byte];
610            if let Some(space_pos) = seg.rfind(' ') {
611                lines.push(&remaining[..space_pos]);
612                // Skip the space
613                remaining = &remaining[space_pos + 1..];
614            } else {
615                // No space found — hard break at max_width
616                lines.push(seg);
617                remaining = &remaining[break_byte..];
618            }
619        }
620    }
621
622    lines
623}
624
625impl Component for TextInput {
626    fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
627        TextInput::handle_keystroke(self, key)
628    }
629}
630
631/// Widget adapter so `TextInput` can be used with `frame.render_widget`.
632/// The cursor position is stashed in the provided `Option`.
633pub struct TextInputWidget<'a> {
634    input: &'a TextInput,
635    cursor_out: &'a mut Option<Position>,
636}
637
638impl<'a> TextInputWidget<'a> {
639    pub fn new(input: &'a TextInput, cursor_out: &'a mut Option<Position>) -> Self {
640        Self { input, cursor_out }
641    }
642}
643
644impl<'a> Widget for TextInputWidget<'a> {
645    fn render(self, area: Rect, buf: &mut Buffer) {
646        let result = self.input.render(area, buf);
647        *self.cursor_out = Some(result.cursor_position);
648    }
649}