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
17pub struct TextInput {
19 buf: String,
20 cursor: usize,
22 wrap_width: Cell<u16>,
26}
27
28pub struct RenderResult {
30 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 pub fn insert_char(&mut self, ch: char) {
52 self.buf.insert(self.cursor, ch);
53 self.cursor += ch.len_utf8();
54 }
55
56 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 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 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 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 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 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 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 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 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 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 pub fn move_word_left(&mut self) {
233 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 if let Some((i, _)) = trimmed
242 .char_indices()
243 .rev()
244 .find(|(_, c)| c.is_whitespace())
245 {
246 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 pub fn move_word_right(&mut self) {
259 let after = &self.buf[self.cursor..];
260 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 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 pub fn insert_newline(&mut self) {
284 self.insert_char('\n');
285 }
286
287 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 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 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 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 KeyCode::Char('j') if ctrl => {
340 self.insert_newline();
341 KeyResult::Captured
342 }
343
344 KeyCode::Char(_) if ctrl => KeyResult::NotCaptured,
346
347 KeyCode::Backspace if alt => {
349 self.delete_word_left();
350 KeyResult::Captured
351 }
352
353 KeyCode::Enter if alt => {
355 self.insert_newline();
356 KeyResult::Captured
357 }
358
359 KeyCode::Enter => KeyResult::NotCaptured,
361
362 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 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 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 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 pub fn render(&self, area: Rect, buf: &mut Buffer) -> RenderResult {
456 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 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 let line_full = line.width() >= inner.width as usize;
498 if offset == line.len() && line_full {
499 continue;
502 }
503
504 cursor_row = row_idx as u16;
505 cursor_col = col as u16;
506 found_cursor = true;
507 }
508 }
509
510 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 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
554fn wrap_lines<'a>(text: &'a str, max_width: usize) -> Vec<&'a str> {
558 if text.is_empty() {
559 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 for segment in text.split('\n') {
571 if segment.is_empty() {
574 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 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 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 let seg = &remaining[..break_byte];
610 if let Some(space_pos) = seg.rfind(' ') {
611 lines.push(&remaining[..space_pos]);
612 remaining = &remaining[space_pos + 1..];
614 } else {
615 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
631pub 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}