Skip to main content

comb/widgets/
input.rs

1//! Single-line text field matching the hive input strip: borderless tinted
2//! band, `→` prompt, placeholder, hardware cursor via returned position.
3
4use crate::core::buffer::Buffer;
5use crate::core::geom::Rect;
6use crate::core::style::{Modifier, Style};
7use crate::widgets::Palette;
8
9const PROMPT: &str = "→ ";
10const PROMPT_W: usize = 2;
11
12#[derive(Default)]
13pub struct TextInput {
14    pub value: String,
15    pub cursor: usize,
16    pub placeholder: String,
17}
18
19impl TextInput {
20    pub fn with_placeholder(placeholder: impl Into<String>) -> Self {
21        TextInput {
22            placeholder: placeholder.into(),
23            ..Default::default()
24        }
25    }
26
27    fn byte_at(&self, char_idx: usize) -> usize {
28        self.value
29            .char_indices()
30            .nth(char_idx)
31            .map(|(b, _)| b)
32            .unwrap_or(self.value.len())
33    }
34
35    fn char_count(&self) -> usize {
36        self.value.chars().count()
37    }
38
39    pub fn insert(&mut self, c: char) {
40        if c == '\0' || (c.is_control() && c != '\t') {
41            return;
42        }
43        let b = self.byte_at(self.cursor);
44        self.value.insert(b, c);
45        self.cursor += 1;
46    }
47
48    /// Insert clipboard / bracketed-paste text at the cursor.
49    /// Newlines become spaces (single-line field). Other C0 controls are dropped.
50    pub fn insert_str(&mut self, text: &str) {
51        for c in text.chars() {
52            match c {
53                '\n' | '\r' => self.insert(' '),
54                c if c.is_control() && c != '\t' => {}
55                c => self.insert(c),
56            }
57        }
58    }
59
60    pub fn backspace(&mut self) {
61        if self.cursor == 0 {
62            return;
63        }
64        let start = self.byte_at(self.cursor - 1);
65        let end = self.byte_at(self.cursor);
66        self.value.replace_range(start..end, "");
67        self.cursor -= 1;
68    }
69
70    pub fn left(&mut self) {
71        self.cursor = self.cursor.saturating_sub(1);
72    }
73
74    pub fn right(&mut self) {
75        if self.cursor < self.char_count() {
76            self.cursor += 1;
77        }
78    }
79
80    pub fn take(&mut self) -> String {
81        self.cursor = 0;
82        std::mem::take(&mut self.value)
83    }
84
85    pub fn is_empty(&self) -> bool {
86        self.value.is_empty()
87    }
88
89    /// Draw the strip. Returns `(x, y)` for the hardware cursor.
90    pub fn render(&self, buf: &mut Buffer, area: Rect, pal: &Palette) -> Option<(u16, u16)> {
91        if area.height < 3 || area.width < 4 {
92            return None;
93        }
94
95        let strip = pal.panel;
96        buf.paint(area, strip);
97
98        let text_y = area.y + 1;
99        let row = Rect::new(area.x + 1, text_y, area.width.saturating_sub(2), 1);
100        if row.is_empty() {
101            return None;
102        }
103
104        buf.paint(row, strip);
105        let on = |st: Style| st.patch(strip);
106        let prompt = on(pal.accent);
107        let body = on(pal.normal);
108        let ghost = on(pal.normal).add(Modifier::DIM | Modifier::ITALIC);
109
110        buf.set_str(row.x, text_y, PROMPT, prompt);
111
112        let text_x = row.x + PROMPT_W as u16;
113        let avail = row.width.saturating_sub(PROMPT_W as u16) as usize;
114
115        if self.value.is_empty() {
116            buf.set_str(text_x, text_y, &self.placeholder, ghost);
117            pad_row(
118                buf,
119                row,
120                text_x + self.placeholder.chars().count() as u16,
121                strip,
122            );
123            return Some((text_x, text_y));
124        }
125
126        let chars: Vec<char> = self.value.chars().collect();
127        let cursor = self.cursor.min(chars.len());
128        let mut start = 0usize;
129        if cursor > avail.saturating_sub(1) {
130            start = cursor.saturating_sub(avail.saturating_sub(1));
131        }
132        let visible: String = chars.iter().skip(start).take(avail).collect();
133        buf.set_str(text_x, text_y, &visible, body);
134        pad_row(buf, row, text_x + visible.chars().count() as u16, strip);
135
136        let cx = text_x + (cursor.saturating_sub(start)) as u16;
137        Some((cx.min(row.right().saturating_sub(1)), text_y))
138    }
139}
140
141fn pad_row(buf: &mut Buffer, row: Rect, from_x: u16, bg: Style) {
142    for x in from_x..row.right() {
143        buf.set(x, row.y, ' ', bg);
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::core::geom::Size;
151    use crate::core::style::Color;
152    use crate::term::terminal::render;
153
154    fn pal() -> Palette {
155        let bg = Style::new().bg(Color::rgb(0x26, 0x26, 0x26));
156        Palette {
157            panel: bg,
158            border: Style::new().fg(Color::rgb(0x6a, 0x6a, 0x6a)),
159            normal: Style::new().fg(Color::rgb(0xd4, 0xd4, 0xd4)),
160            accent: Style::new().fg(Color::rgb(0xe6, 0xe6, 0xe6)),
161            selected: Style::new()
162                .fg(Color::rgb(0x12, 0x12, 0x12))
163                .bg(Color::rgb(0xd8, 0xd8, 0xd8)),
164            track: Style::new(),
165            thumb: Style::new(),
166        }
167    }
168
169    #[test]
170    fn text_row_keeps_strip_background() {
171        let input = TextInput::with_placeholder("type here");
172        let buf = render(Size::new(40, 5), |f| {
173            let _ = input.render(f.buffer(), Rect::new(1, 1, 36, 3), &pal());
174        });
175        for x in 2..36 {
176            let cell = buf.get(x, 2).unwrap();
177            assert_eq!(cell.style.bg, Some(Color::rgb(0x26, 0x26, 0x26)), "x={x}");
178        }
179    }
180
181    #[test]
182    fn returns_cursor_on_text_row() {
183        let mut input = TextInput::with_placeholder("x");
184        input.insert('a');
185        let mut cursor = None;
186        let _ = render(Size::new(30, 5), |f| {
187            cursor = input.render(f.buffer(), Rect::new(1, 1, 26, 3), &pal());
188        });
189        // area(1,1) → row.x=2 → text after "→ " at x=4 → caret after 'a' at x=5
190        assert_eq!(cursor, Some((5, 2)));
191    }
192}