saorsa-tui 0.4.0

Retained-mode, CSS-styled terminal UI framework
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Scrollable log widget that displays styled entries.
//!
//! Each entry is a line of [`Segment`]s. The log supports vertical
//! scrolling via keyboard and optional auto-scrolling to the bottom
//! when new entries are added.

use crate::buffer::ScreenBuffer;
use crate::cell::Cell;
use crate::event::{Event, KeyCode, KeyEvent};
use crate::geometry::Rect;
use crate::segment::Segment;
use crate::style::Style;
use crate::text::truncate_to_display_width;
use unicode_width::UnicodeWidthStr;

use super::{BorderStyle, EventResult, InteractiveWidget, Widget};

/// A scrollable log widget that displays styled entries.
///
/// Each entry is a vector of [`Segment`]s representing one line.
/// Supports vertical scrolling and optional auto-scroll to bottom.
#[derive(Clone, Debug)]
pub struct RichLog {
    /// Log entries: each entry is a line of segments.
    entries: Vec<Vec<Segment>>,
    /// Index of the first visible entry.
    scroll_offset: usize,
    /// Base style for the log area.
    style: Style,
    /// Whether to auto-scroll to bottom when entries are added.
    auto_scroll: bool,
    /// Border style (optional).
    border: BorderStyle,
}

impl RichLog {
    /// Create a new empty log.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            scroll_offset: 0,
            style: Style::default(),
            auto_scroll: true,
            border: BorderStyle::None,
        }
    }

    /// Set the base style for the log area.
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set the border style.
    #[must_use]
    pub fn with_border(mut self, border: BorderStyle) -> Self {
        self.border = border;
        self
    }

    /// Get the current base style.
    pub fn base_style(&self) -> &Style {
        &self.style
    }

    /// Set the base style.
    pub fn set_base_style(&mut self, style: Style) {
        self.style = style;
    }

    /// Get the current border style kind.
    pub fn border_style_kind(&self) -> BorderStyle {
        self.border
    }

    /// Set the border style kind.
    pub fn set_border(&mut self, border: BorderStyle) {
        self.border = border;
    }

    /// Enable or disable auto-scrolling to the bottom on new entries.
    #[must_use]
    pub fn with_auto_scroll(mut self, enabled: bool) -> Self {
        self.auto_scroll = enabled;
        self
    }

    /// Add a log entry (single line of segments).
    pub fn push(&mut self, entry: Vec<Segment>) {
        self.entries.push(entry);
        if self.auto_scroll {
            // Will be applied on next render based on visible height;
            // for now, set offset to show last entry.
            // We use saturating_sub to handle the case where we don't know
            // the visible height yet - scroll_to_bottom() can be called
            // explicitly or it adjusts in render.
            self.scroll_offset = self.entries.len().saturating_sub(1);
        }
    }

    /// Add a plain text entry (convenience method).
    pub fn push_text(&mut self, text: &str) {
        self.entries.push(vec![Segment::new(text)]);
        if self.auto_scroll {
            self.scroll_offset = self.entries.len().saturating_sub(1);
        }
    }

    /// Clear all entries and reset scroll.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.scroll_offset = 0;
    }

    /// Get total entry count.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if the log has no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Scroll to the bottom (last entry visible).
    pub fn scroll_to_bottom(&mut self) {
        if !self.entries.is_empty() {
            self.scroll_offset = self.entries.len().saturating_sub(1);
        }
    }

    /// Scroll to the top (first entry visible).
    pub fn scroll_to_top(&mut self) {
        self.scroll_offset = 0;
    }

    /// Get the current scroll offset.
    pub fn scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    /// Scroll up by `lines`, clamping at 0.
    pub fn scroll_up_by(&mut self, lines: usize) {
        self.scroll_offset = self.scroll_offset.saturating_sub(lines);
        self.auto_scroll = false;
    }

    /// Scroll down by `lines`, clamping at the last entry.
    pub fn scroll_down_by(&mut self, lines: usize) {
        if self.entries.is_empty() {
            return;
        }
        let max = self.entries.len().saturating_sub(1);
        self.scroll_offset = (self.scroll_offset + lines).min(max);
        self.auto_scroll = false;
    }
}

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

impl Widget for RichLog {
    fn render(&self, area: Rect, buf: &mut ScreenBuffer) {
        if area.size.width == 0 || area.size.height == 0 {
            return;
        }

        // Render border if any
        super::border::render_border(area, self.border, self.style.clone(), buf);

        let inner = super::border::inner_area(area, self.border);
        if inner.size.width == 0 || inner.size.height == 0 {
            return;
        }

        let height = inner.size.height as usize;
        let width = inner.size.width as usize;

        // Clamp scroll offset (use a local copy since render takes &self)
        let max_offset = self.entries.len().saturating_sub(height.max(1));
        let scroll = self.scroll_offset.min(max_offset);

        let visible_end = (scroll + height).min(self.entries.len());

        for (row, entry_idx) in (scroll..visible_end).enumerate() {
            let y = inner.position.y + row as u16;
            if let Some(entry) = self.entries.get(entry_idx) {
                let mut col: u16 = 0;
                for segment in entry {
                    if col as usize >= width {
                        break;
                    }
                    let remaining = width.saturating_sub(col as usize);
                    let truncated = truncate_to_display_width(&segment.text, remaining);
                    for ch in truncated.chars() {
                        let char_w = UnicodeWidthStr::width(ch.encode_utf8(&mut [0; 4]) as &str);
                        if col as usize + char_w > width {
                            break;
                        }
                        let x = inner.position.x + col;
                        buf.set(x, y, Cell::new(ch.to_string(), segment.style.clone()));
                        col += char_w as u16;
                    }
                }
            }
        }
    }
}

impl InteractiveWidget for RichLog {
    fn handle_event(&mut self, event: &Event) -> EventResult {
        let Event::Key(KeyEvent { code, .. }) = event else {
            return EventResult::Ignored;
        };

        match code {
            KeyCode::Up => {
                if self.scroll_offset > 0 {
                    self.scroll_offset -= 1;
                    self.auto_scroll = false;
                }
                EventResult::Consumed
            }
            KeyCode::Down => {
                if !self.entries.is_empty()
                    && self.scroll_offset < self.entries.len().saturating_sub(1)
                {
                    self.scroll_offset += 1;
                    self.auto_scroll = false;
                }
                EventResult::Consumed
            }
            KeyCode::PageUp => {
                // Scroll by a page (assume ~20 lines if we don't know height)
                let page = 20;
                self.scroll_offset = self.scroll_offset.saturating_sub(page);
                self.auto_scroll = false;
                EventResult::Consumed
            }
            KeyCode::PageDown => {
                let page = 20;
                if !self.entries.is_empty() {
                    self.scroll_offset =
                        (self.scroll_offset + page).min(self.entries.len().saturating_sub(1));
                    self.auto_scroll = false;
                }
                EventResult::Consumed
            }
            KeyCode::Home => {
                self.scroll_to_top();
                self.auto_scroll = false;
                EventResult::Consumed
            }
            KeyCode::End => {
                self.scroll_to_bottom();
                // Scrolling to end re-enables auto_scroll behavior
                EventResult::Consumed
            }
            _ => EventResult::Ignored,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::geometry::Size;
    use crate::style::Style;

    fn make_segment(text: &str) -> Segment {
        Segment::new(text)
    }

    fn styled_segment(text: &str, style: Style) -> Segment {
        Segment::styled(text, style)
    }

    #[test]
    fn new_log_is_empty() {
        let log = RichLog::new();
        assert!(log.is_empty());
        assert_eq!(log.len(), 0);
        assert_eq!(log.scroll_offset(), 0);
    }

    #[test]
    fn default_matches_new() {
        let log: RichLog = Default::default();
        assert!(log.is_empty());
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn push_adds_entries() {
        let mut log = RichLog::new();
        log.push(vec![make_segment("line 1")]);
        log.push(vec![make_segment("line 2")]);
        assert_eq!(log.len(), 2);
        assert!(!log.is_empty());
    }

    #[test]
    fn push_text_convenience() {
        let mut log = RichLog::new();
        log.push_text("hello");
        assert_eq!(log.len(), 1);
    }

    #[test]
    fn clear_resets() {
        let mut log = RichLog::new();
        log.push_text("a");
        log.push_text("b");
        log.clear();
        assert!(log.is_empty());
        assert_eq!(log.scroll_offset(), 0);
    }

    #[test]
    fn render_empty_log() {
        let log = RichLog::new();
        let mut buf = ScreenBuffer::new(Size::new(20, 5));
        log.render(Rect::new(0, 0, 20, 5), &mut buf);
        // Should not panic; area remains blank
        assert_eq!(buf.get(0, 0).map(|c| c.grapheme.as_str()), Some(" "));
    }

    #[test]
    fn render_with_entries() {
        let mut log = RichLog::new().with_auto_scroll(false);
        log.push_text("hello");
        log.push_text("world");

        let mut buf = ScreenBuffer::new(Size::new(10, 5));
        log.render(Rect::new(0, 0, 10, 5), &mut buf);

        assert_eq!(buf.get(0, 0).map(|c| c.grapheme.as_str()), Some("h"));
        assert_eq!(buf.get(1, 0).map(|c| c.grapheme.as_str()), Some("e"));
        assert_eq!(buf.get(0, 1).map(|c| c.grapheme.as_str()), Some("w"));
    }

    #[test]
    fn render_with_multi_segment_entries() {
        let mut log = RichLog::new().with_auto_scroll(false);
        let bold = Style::new().bold(true);
        log.push(vec![styled_segment("bold", bold), make_segment(" normal")]);

        let mut buf = ScreenBuffer::new(Size::new(20, 5));
        log.render(Rect::new(0, 0, 20, 5), &mut buf);

        // 'b' should be bold
        let cell_b = buf.get(0, 0);
        assert!(cell_b.is_some());
        assert_eq!(cell_b.map(|c| c.grapheme.as_str()), Some("b"));
        assert!(cell_b.map(|c| c.style.bold).unwrap_or(false));

        // ' ' after "bold" should be normal
        let cell_space = buf.get(4, 0);
        assert_eq!(cell_space.map(|c| c.grapheme.as_str()), Some(" "));
    }

    #[test]
    fn render_with_border() {
        let mut log = RichLog::new()
            .with_border(BorderStyle::Single)
            .with_auto_scroll(false);
        log.push_text("hi");

        let mut buf = ScreenBuffer::new(Size::new(10, 5));
        log.render(Rect::new(0, 0, 10, 5), &mut buf);

        // Top-left corner should be box drawing char
        let corner = buf.get(0, 0).map(|c| c.grapheme.as_str());
        assert_eq!(corner, Some("\u{250c}"));

        // Content at (1, 1) inside border
        assert_eq!(buf.get(1, 1).map(|c| c.grapheme.as_str()), Some("h"));
    }

    #[test]
    fn scroll_operations() {
        let mut log = RichLog::new().with_auto_scroll(false);
        for i in 0..20 {
            log.push_text(&format!("line {i}"));
        }

        log.scroll_to_bottom();
        assert_eq!(log.scroll_offset(), 19);

        log.scroll_to_top();
        assert_eq!(log.scroll_offset(), 0);
    }

    #[test]
    fn auto_scroll_on_push() {
        let mut log = RichLog::new().with_auto_scroll(true);
        log.push_text("a");
        assert_eq!(log.scroll_offset(), 0);
        log.push_text("b");
        assert_eq!(log.scroll_offset(), 1);
        log.push_text("c");
        assert_eq!(log.scroll_offset(), 2);
    }

    #[test]
    fn manual_scroll_disables_auto_scroll() {
        let mut log = RichLog::new().with_auto_scroll(true);
        for _ in 0..10 {
            log.push_text("line");
        }

        // Scroll up manually
        let event = Event::Key(KeyEvent::plain(KeyCode::Up));
        let result = log.handle_event(&event);
        assert_eq!(result, EventResult::Consumed);

        // Auto-scroll should now be disabled
        let prev_offset = log.scroll_offset();
        log.push_text("new line");
        // Offset should NOT auto-scroll because auto_scroll is disabled
        assert_eq!(log.scroll_offset(), prev_offset);
    }

    #[test]
    fn keyboard_navigation() {
        let mut log = RichLog::new().with_auto_scroll(false);
        for i in 0..30 {
            log.push_text(&format!("line {i}"));
        }

        // Down key
        let down = Event::Key(KeyEvent::plain(KeyCode::Down));
        log.handle_event(&down);
        assert_eq!(log.scroll_offset(), 1);

        // Up key
        let up = Event::Key(KeyEvent::plain(KeyCode::Up));
        log.handle_event(&up);
        assert_eq!(log.scroll_offset(), 0);

        // Up at top stays at 0
        log.handle_event(&up);
        assert_eq!(log.scroll_offset(), 0);

        // Page down
        let pgdn = Event::Key(KeyEvent::plain(KeyCode::PageDown));
        log.handle_event(&pgdn);
        assert_eq!(log.scroll_offset(), 20);

        // Page up
        let pgup = Event::Key(KeyEvent::plain(KeyCode::PageUp));
        log.handle_event(&pgup);
        assert_eq!(log.scroll_offset(), 0);

        // End key
        let end = Event::Key(KeyEvent::plain(KeyCode::End));
        log.handle_event(&end);
        assert_eq!(log.scroll_offset(), 29);

        // Home key
        let home = Event::Key(KeyEvent::plain(KeyCode::Home));
        log.handle_event(&home);
        assert_eq!(log.scroll_offset(), 0);
    }

    #[test]
    fn empty_log_keyboard_events_graceful() {
        let mut log = RichLog::new();
        let down = Event::Key(KeyEvent::plain(KeyCode::Down));
        let result = log.handle_event(&down);
        assert_eq!(result, EventResult::Consumed);
        assert_eq!(log.scroll_offset(), 0);
    }

    #[test]
    fn utf8_safety_wide_chars() {
        let mut log = RichLog::new().with_auto_scroll(false);
        log.push_text("日本語テスト");
        log.push_text("Hello 🎉 World");

        let mut buf = ScreenBuffer::new(Size::new(10, 5));
        log.render(Rect::new(0, 0, 10, 5), &mut buf);

        // Should not panic, and content should be truncated to width
        let first_cell = buf.get(0, 0).map(|c| c.grapheme.as_str());
        assert_eq!(first_cell, Some(""));
    }

    #[test]
    fn overflow_truncation() {
        let mut log = RichLog::new().with_auto_scroll(false);
        log.push_text("This is a very long line that should be truncated to fit");

        let mut buf = ScreenBuffer::new(Size::new(10, 1));
        log.render(Rect::new(0, 0, 10, 1), &mut buf);

        // Only first 10 chars should appear: "This is a "
        assert_eq!(buf.get(0, 0).map(|c| c.grapheme.as_str()), Some("T"));
        assert_eq!(buf.get(4, 0).map(|c| c.grapheme.as_str()), Some(" "));
        assert_eq!(buf.get(5, 0).map(|c| c.grapheme.as_str()), Some("i"));
    }

    #[test]
    fn unhandled_event_returns_ignored() {
        let mut log = RichLog::new();
        let event = Event::Key(KeyEvent::plain(KeyCode::Char('a')));
        assert_eq!(log.handle_event(&event), EventResult::Ignored);
    }

    #[test]
    fn builder_pattern() {
        let log = RichLog::new()
            .with_style(Style::new().bold(true))
            .with_border(BorderStyle::Rounded)
            .with_auto_scroll(false);

        assert!(!log.auto_scroll);
        assert!(matches!(log.border, BorderStyle::Rounded));
    }
}