tuillem-tui 0.1.4

Ratatui TUI layer for tuillem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use ratatui::{
    Frame,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};

use crate::theme::Theme;

#[derive(Debug, Clone)]
pub struct Input {
    pub content: String,
    pub cursor_pos: usize,
    pub focused: bool,
}

impl Input {
    pub fn new() -> Self {
        Self {
            content: String::new(),
            cursor_pos: 0,
            focused: true,
        }
    }

    pub fn render(
        &self,
        frame: &mut Frame,
        area: Rect,
        current_model: &str,
        is_streaming: bool,
        theme: &Theme,
    ) {
        let status = if is_streaming { " streaming... " } else { "" };

        let title_line = Line::from(vec![
            Span::styled(
                " tuillem ",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(status, Style::default().fg(theme.warning)),
        ]);

        let bottom_line = Line::from(vec![
            Span::styled(
                format!(" {} ", current_model),
                Style::default().fg(theme.thinking_fg),
            ),
            Span::styled(
                " Enter:send | Alt-Ent:newline | C-x:editor | C-k:commands | C-h:help ",
                Style::default().fg(theme.thinking_fg),
            ),
        ]);

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(if self.focused {
                Style::default().fg(theme.accent)
            } else {
                theme.border_style()
            })
            .title_top(title_line)
            .title_bottom(bottom_line)
            .style(Style::default().fg(theme.fg).bg(theme.bg));

        let inner = block.inner(area);
        frame.render_widget(block, area);

        let display = if self.content.is_empty() {
            Paragraph::new(Span::styled(
                "Type a message...",
                Style::default().fg(theme.thinking_fg).bg(theme.bg),
            ))
        } else {
            Paragraph::new(ratatui::text::Text::from(self.content.as_str().to_owned()))
                .style(Style::default().fg(theme.fg).bg(theme.bg))
                .wrap(Wrap { trim: false })
        };

        // Scroll the input so the cursor line is always visible
        let (cx, cy) = compute_cursor_pos(&self.content, self.cursor_pos, inner.width as usize);
        let input_scroll = if cy as u16 >= inner.height {
            (cy as u16) - inner.height + 1
        } else {
            0
        };
        let display = display.scroll((input_scroll, 0));
        frame.render_widget(display, inner);

        // Show cursor — simulate ratatui's word wrapping to find cursor position
        if self.focused && inner.width > 0 && inner.height > 0 {
            let cursor_x = inner.x + cx as u16;
            let cursor_y = inner.y + (cy as u16).saturating_sub(input_scroll);
            if cursor_x < inner.x + inner.width && cursor_y < inner.y + inner.height {
                frame.set_cursor_position((cursor_x, cursor_y));
            }
        }
    }

    pub fn insert_char(&mut self, c: char) {
        self.content.insert(self.cursor_pos, c);
        self.cursor_pos += c.len_utf8();
    }

    pub fn insert_str(&mut self, s: &str) {
        self.content.insert_str(self.cursor_pos, s);
        self.cursor_pos += s.len();
    }

    pub fn delete_char(&mut self) {
        if self.cursor_pos < self.content.len() {
            let next_char = self.content[self.cursor_pos..].chars().next();
            if let Some(c) = next_char {
                self.content.remove(self.cursor_pos);
                let _ = c;
            }
        }
    }

    pub fn backspace(&mut self) {
        if self.cursor_pos > 0 {
            let prev = self.content[..self.cursor_pos]
                .char_indices()
                .last()
                .map(|(i, _)| i);
            if let Some(pos) = prev {
                self.content.remove(pos);
                self.cursor_pos = pos;
            }
        }
    }

    pub fn delete_word_backward(&mut self) {
        if self.cursor_pos == 0 {
            return;
        }
        let before = &self.content[..self.cursor_pos];
        // Skip trailing whitespace, then delete back to next whitespace
        let end = before.trim_end().len();
        let start = before[..end]
            .rfind(|c: char| c.is_whitespace())
            .map_or(0, |i| i + 1);
        self.content.drain(start..self.cursor_pos);
        self.cursor_pos = start;
    }

    pub fn move_left(&mut self) {
        if self.cursor_pos > 0 {
            let prev = self.content[..self.cursor_pos]
                .char_indices()
                .last()
                .map(|(i, _)| i)
                .unwrap_or(0);
            self.cursor_pos = prev;
        }
    }

    pub fn move_right(&mut self) {
        if self.cursor_pos < self.content.len() {
            let next = self.content[self.cursor_pos..]
                .chars()
                .next()
                .map(|c| self.cursor_pos + c.len_utf8())
                .unwrap_or(self.content.len());
            self.cursor_pos = next;
        }
    }

    pub fn move_home(&mut self) {
        self.cursor_pos = 0;
    }

    pub fn move_end(&mut self) {
        self.cursor_pos = self.content.len();
    }

    /// Move cursor up one line. Returns false if already on the first line.
    pub fn move_up(&mut self) -> bool {
        let before = &self.content[..self.cursor_pos];
        if let Some(nl_pos) = before.rfind('\n') {
            // Column offset on current line
            let col = before[nl_pos + 1..].chars().count();
            // Find start of previous line
            let prev_line_start = before[..nl_pos].rfind('\n').map_or(0, |p| p + 1);
            let prev_line = &self.content[prev_line_start..nl_pos];
            let target_col = col.min(prev_line.chars().count());
            self.cursor_pos = prev_line_start
                + prev_line
                    .chars()
                    .take(target_col)
                    .map(|c| c.len_utf8())
                    .sum::<usize>();
            true
        } else {
            false
        }
    }

    /// Move cursor down one line. Returns false if already on the last line.
    pub fn move_down(&mut self) -> bool {
        let after = &self.content[self.cursor_pos..];
        if let Some(nl_offset) = after.find('\n') {
            // Column offset on current line
            let before = &self.content[..self.cursor_pos];
            let current_line_start = before.rfind('\n').map_or(0, |p| p + 1);
            let col = before[current_line_start..].chars().count();
            // Next line starts after the newline
            let next_line_start = self.cursor_pos + nl_offset + 1;
            let next_line_end = self.content[next_line_start..]
                .find('\n')
                .map_or(self.content.len(), |p| next_line_start + p);
            let next_line = &self.content[next_line_start..next_line_end];
            let target_col = col.min(next_line.chars().count());
            self.cursor_pos = next_line_start
                + next_line
                    .chars()
                    .take(target_col)
                    .map(|c| c.len_utf8())
                    .sum::<usize>();
            true
        } else {
            false
        }
    }

    /// Take the content out, resetting the input. Returns the taken content.
    pub fn take_content(&mut self) -> String {
        let content = std::mem::take(&mut self.content);
        self.cursor_pos = 0;
        content
    }

    /// Set content and move cursor to end.
    pub fn set_content(&mut self, content: String) {
        self.cursor_pos = content.len();
        self.content = content;
    }
}

impl Default for Input {
    fn default() -> Self {
        Self::new()
    }
}

/// Compute visual (x, y) cursor position by simulating word wrapping.
/// Matches ratatui's `Wrap { trim: false }` behavior.
fn compute_cursor_pos(text: &str, byte_pos: usize, wrap_width: usize) -> (usize, usize) {
    if wrap_width == 0 {
        return (0, 0);
    }

    let text_before = &text[..byte_pos];
    let mut x = 0usize;
    let mut y = 0usize;

    // Process line by line (hard breaks from \n)
    for (line_idx, line) in text_before.split('\n').enumerate() {
        if line_idx > 0 {
            y += 1;
        }

        // Simulate word wrapping within this line
        let mut col = 0usize;
        let mut chars = line.chars().peekable();

        while chars.peek().is_some() {
            // Find next word and trailing spaces
            let mut word = String::new();
            // Consume spaces first
            while let Some(&c) = chars.peek() {
                if c == ' ' {
                    word.push(c);
                    chars.next();
                } else {
                    break;
                }
            }
            // Consume non-space chars
            let space_len = word.len();
            while let Some(&c) = chars.peek() {
                if c == ' ' {
                    break;
                }
                word.push(c);
                chars.next();
            }

            let word_len = word.len();

            if col == 0 {
                // Start of line — always place the word
                col = word_len;
            } else if col + word_len <= wrap_width {
                // Fits on current line
                col += word_len;
            } else {
                // Doesn't fit — wrap to next line
                y += 1;
                // In wrap mode, leading spaces on wrapped line are kept (trim: false)
                col = word_len - space_len; // just the non-space part on new line
                if col == 0 && space_len > 0 {
                    col = word_len; // all spaces — keep them
                }
            }
        }

        x = col;
    }

    (x, y)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_and_backspace() {
        let mut input = Input::new();
        input.insert_char('H');
        input.insert_char('i');
        assert_eq!(input.content, "Hi");
        assert_eq!(input.cursor_pos, 2);

        input.backspace();
        assert_eq!(input.content, "H");
        assert_eq!(input.cursor_pos, 1);

        input.backspace();
        assert_eq!(input.content, "");
        assert_eq!(input.cursor_pos, 0);

        // Backspace on empty does nothing
        input.backspace();
        assert_eq!(input.content, "");
        assert_eq!(input.cursor_pos, 0);
    }

    #[test]
    fn test_cursor_movement() {
        let mut input = Input::new();
        input.set_content("Hello".to_string());
        assert_eq!(input.cursor_pos, 5);

        input.move_home();
        assert_eq!(input.cursor_pos, 0);

        input.move_right();
        assert_eq!(input.cursor_pos, 1);

        input.move_end();
        assert_eq!(input.cursor_pos, 5);

        input.move_left();
        assert_eq!(input.cursor_pos, 4);

        input.move_home();
        input.move_left();
        assert_eq!(input.cursor_pos, 0);

        input.move_end();
        input.move_right();
        assert_eq!(input.cursor_pos, 5);
    }

    #[test]
    fn test_take_content() {
        let mut input = Input::new();
        input.set_content("Hello world".to_string());
        let taken = input.take_content();
        assert_eq!(taken, "Hello world");
        assert_eq!(input.content, "");
        assert_eq!(input.cursor_pos, 0);
    }

    #[test]
    fn test_insert_str() {
        let mut input = Input::new();
        input.insert_str("Hello\nWorld");
        assert_eq!(input.content, "Hello\nWorld");
        assert_eq!(input.cursor_pos, 11);

        // Insert in the middle
        input.cursor_pos = 5;
        input.insert_str(" there");
        assert_eq!(input.content, "Hello there\nWorld");
    }

    #[test]
    fn test_move_up_down_single_line() {
        let mut input = Input::new();
        input.set_content("Hello".to_string());

        // Can't move up or down on a single line
        assert!(!input.move_up());
        assert!(!input.move_down());
    }

    #[test]
    fn test_move_up_down_multiline() {
        let mut input = Input::new();
        input.set_content("abc\ndef\nghi".to_string());
        // Cursor at end: line 2 ("ghi"), col 3
        assert_eq!(input.cursor_pos, 11);

        // Move up: line 1 ("def"), col 3
        assert!(input.move_up());
        assert_eq!(input.cursor_pos, 7); // "abc\ndef" = 7

        // Move up: line 0 ("abc"), col 3
        assert!(input.move_up());
        assert_eq!(input.cursor_pos, 3); // "abc" = 3

        // Can't move up further
        assert!(!input.move_up());
        assert_eq!(input.cursor_pos, 3);

        // Move down: line 1, col 3
        assert!(input.move_down());
        assert_eq!(input.cursor_pos, 7);

        // Move down: line 2, col 3
        assert!(input.move_down());
        assert_eq!(input.cursor_pos, 11);

        // Can't move down further
        assert!(!input.move_down());
    }

    #[test]
    fn test_move_up_clamps_column() {
        let mut input = Input::new();
        input.set_content("abcdef\nhi".to_string());
        // Cursor at end of "hi" (line 1, col 2)
        assert_eq!(input.cursor_pos, 9);

        // Move up: line 0 has 6 chars, but col is 2 so lands at col 2
        assert!(input.move_up());
        assert_eq!(input.cursor_pos, 2);

        // Move down: line 1 has 2 chars, col 2 clamps to end
        assert!(input.move_down());
        assert_eq!(input.cursor_pos, 9);
    }

    #[test]
    fn test_move_up_down_utf8() {
        let mut input = Input::new();
        // "café" is 5 bytes (é = 2 bytes), "hi" is 2 bytes
        input.set_content("café\nhi".to_string());
        // Cursor at end
        assert_eq!(input.cursor_pos, 8); // 5 + 1 + 2

        // Move up from "hi" col 2 → "café" col 2 = byte 2 ("ca")
        assert!(input.move_up());
        assert_eq!(input.cursor_pos, 2);

        // Move down from col 2 → "hi" col 2 = byte 8
        assert!(input.move_down());
        assert_eq!(input.cursor_pos, 8);
    }
}