aether-tui 0.2.1

A lightweight terminal UI rendering library for building rich CLI applications
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use crate::diffs::diff::highlight_diff;
use crate::line::Line;
use crate::rendering::frame::{FitOptions, Frame, FramePart};
use crate::rendering::gutter::digit_count;
use crate::rendering::render_context::ViewContext;
use crate::span::Span;
use crate::style::Style;

use crate::{DiffPreview, DiffTag, SplitDiffCell};

const MAX_DIFF_LINES: usize = 20;
pub const MIN_SPLIT_WIDTH: u16 = 80;
pub const MIN_GUTTER_WIDTH: usize = 3;
pub const SEPARATOR: &str = " ";
pub const SEPARATOR_WIDTH: usize = 1;
const SEPARATOR_WIDTH_U16: u16 = 1;
const LEFT_INNER_PAD: usize = 1;

/// Which pane a [`render_cell`] call is rendering
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Left,
    Right,
}

/// Renders a diff preview, choosing split or unified based on terminal width
/// and whether the diff has removals.
///
/// For new files (only additions, no removals), uses unified view since
/// split view would have an empty left panel.
pub fn render_diff(preview: &DiffPreview, context: &ViewContext) -> Vec<Line> {
    let has_removals = preview.lines.iter().any(|l| l.tag == DiffTag::Removed);

    if context.size.width >= MIN_SPLIT_WIDTH && has_removals {
        highlight_split_diff(preview, context)
    } else {
        highlight_diff(preview, context)
    }
}

/// Compute the per-pane line-number gutter width: the number of decimal
/// digits in the largest line number across either pane in `preview`, plus
/// one for the trailing space, floored at [`MIN_GUTTER_WIDTH`].
pub fn gutter_width_for_preview(preview: &DiffPreview) -> usize {
    let max_line_no = preview
        .rows
        .iter()
        .flat_map(|row| {
            row.left
                .as_ref()
                .and_then(|c| c.line_number)
                .into_iter()
                .chain(row.right.as_ref().and_then(|c| c.line_number))
        })
        .max()
        .unwrap_or(0);
    (digit_count(max_line_no) + 1).max(MIN_GUTTER_WIDTH)
}

fn highlight_split_diff(preview: &DiffPreview, context: &ViewContext) -> Vec<Line> {
    let theme = &context.theme;
    let terminal_width = context.size.width as usize;
    let gutter_width = gutter_width_for_preview(preview);
    let fixed_overhead = gutter_width * 2 + SEPARATOR_WIDTH + LEFT_INNER_PAD;
    let usable = terminal_width.saturating_sub(fixed_overhead);
    let left_content = usable / 2;
    let right_content = usable - left_content;
    #[allow(clippy::cast_possible_truncation)]
    let left_panel_u16 = (gutter_width + left_content + LEFT_INNER_PAD) as u16;
    #[allow(clippy::cast_possible_truncation)]
    let right_panel_u16 = (gutter_width + right_content) as u16;

    let mut row_frames: Vec<Frame> = Vec::new();
    let mut visual_lines = 0usize;
    let mut rows_consumed = 0usize;

    for row in &preview.rows {
        let left_frame =
            render_cell(row.left.as_ref(), left_content, &preview.lang_hint, Side::Left, gutter_width, context);
        let right_frame =
            render_cell(row.right.as_ref(), right_content, &preview.lang_hint, Side::Right, gutter_width, context);

        let height = left_frame.lines().len().max(right_frame.lines().len());

        if visual_lines + height > MAX_DIFF_LINES && visual_lines > 0 {
            break;
        }

        let sep_line = Line::new(SEPARATOR.to_string());
        let sep_frame = Frame::new(vec![sep_line; height]);
        row_frames.push(Frame::hstack([
            FramePart::new(left_frame, left_panel_u16),
            FramePart::new(sep_frame, SEPARATOR_WIDTH_U16),
            FramePart::new(right_frame, right_panel_u16),
        ]));

        visual_lines += height;
        rows_consumed += 1;
    }

    let mut lines = Frame::vstack(row_frames).into_lines();

    if rows_consumed < preview.rows.len() {
        let remaining = preview.rows.len() - rows_consumed;
        let mut overflow = Line::default();
        overflow.push_styled(format!("    ... {remaining} more lines"), theme.muted());
        lines.push(overflow);
    }

    lines
}

fn blank_panel(width: usize) -> Line {
    let mut line = Line::default();
    line.push_text(" ".repeat(width));
    line
}

pub fn render_cell(
    cell: Option<&SplitDiffCell>,
    content_width: usize,
    lang_hint: &str,
    side: Side,
    gutter_width: usize,
    context: &ViewContext,
) -> Frame {
    let theme = &context.theme;
    let inner_pad = if side == Side::Left { LEFT_INNER_PAD } else { 0 };
    let panel_width = gutter_width + content_width + inner_pad;

    let Some(cell) = cell else {
        return Frame::new(vec![blank_panel(panel_width)]);
    };

    let is_context = cell.tag == DiffTag::Context;
    let bg = match cell.tag {
        DiffTag::Removed => Some(theme.diff_removed_bg()),
        DiffTag::Added => Some(theme.diff_added_bg()),
        DiffTag::Context => None,
    };

    let highlighted = context.highlighter().highlight(&cell.content, lang_hint, theme);

    let content_line = if let Some(hl_line) = highlighted.first() {
        let mut styled_content = Line::default();
        for span in hl_line.spans() {
            let mut span_style = span.style();
            if let Some(bg) = bg {
                span_style.bg = Some(bg);
            }
            if is_context {
                span_style.dim = true;
            }
            styled_content.push_span(Span::with_style(span.text(), span_style));
        }
        styled_content
    } else {
        let fg = match cell.tag {
            DiffTag::Removed => theme.diff_removed_fg(),
            DiffTag::Added => theme.diff_added_fg(),
            DiffTag::Context => theme.code_fg(),
        };
        let mut style = Style::fg(fg);
        if let Some(bg) = bg {
            style = style.bg_color(bg);
        }
        if is_context {
            style.dim = true;
        }
        Line::with_style(&cell.content, style)
    };
    let content_line = match bg {
        Some(bg) => content_line.with_fill(bg),
        None => content_line,
    };

    #[allow(clippy::cast_possible_truncation)]
    let content_width_u16 = content_width as u16;
    let extend_to = content_width + inner_pad;

    let gutter_style = Style::fg(theme.muted());
    let digit_field = gutter_width.saturating_sub(1);
    let head = match cell.line_number {
        Some(num) => Line::with_style(format!("{num:>digit_field$} "), gutter_style),
        None => Line::with_style(" ".repeat(gutter_width), gutter_style),
    };
    let tail = Line::new(" ".repeat(gutter_width));

    Frame::new(vec![content_line])
        .fit(content_width_u16, FitOptions::wrap())
        .map_lines(move |mut line| {
            line.extend_bg_to_width(extend_to);
            line
        })
        .prefix(&head, &tail)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rendering::line::Line;
    use crate::{DiffLine, SplitDiffCell, SplitDiffRow};

    fn test_context_with_width(width: u16) -> ViewContext {
        ViewContext::new((width, 24))
    }

    fn make_split_preview(rows: Vec<SplitDiffRow>) -> DiffPreview {
        DiffPreview { lines: vec![], rows, lang_hint: String::new(), start_line: None }
    }

    fn removed_cell(content: &str, line_num: usize) -> SplitDiffCell {
        SplitDiffCell { tag: DiffTag::Removed, content: content.to_string(), line_number: Some(line_num) }
    }

    fn added_cell(content: &str, line_num: usize) -> SplitDiffCell {
        SplitDiffCell { tag: DiffTag::Added, content: content.to_string(), line_number: Some(line_num) }
    }

    fn style_at_column(line: &Line, col: usize) -> Style {
        let mut current = 0;
        for span in line.spans() {
            let width = crate::display_width_text(span.text());
            if col < current + width {
                return span.style();
            }
            current += width;
        }
        Style::default()
    }

    #[test]
    fn wrapped_split_rows_preserve_neutral_boundary_columns() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell("LEFT_MARK", 1)),
            right: Some(added_cell(&format!("RIGHT_HEAD {} RIGHT_TAIL", "y".repeat(140)), 1)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);

        let first_row = lines
            .iter()
            .position(|line| {
                let text = line.plain_text();
                text.contains("LEFT_MARK") && text.contains("RIGHT_HEAD")
            })
            .expect("expected split row containing both left and right markers");

        let right_start =
            lines[first_row].plain_text().find("RIGHT_HEAD").expect("expected RIGHT_HEAD marker in first split row");

        let wrapped_row = lines
            .iter()
            .enumerate()
            .skip(first_row + 1)
            .find_map(|(index, line)| line.plain_text().contains("RIGHT_TAIL").then_some(index))
            .expect("expected wrapped continuation row containing RIGHT_TAIL marker");

        let wrapped_start = lines[wrapped_row]
            .plain_text()
            .find("RIGHT_TAIL")
            .expect("expected RIGHT_TAIL marker in wrapped continuation row");

        assert!(
            wrapped_start >= right_start,
            "wrapped continuation should not start left of original right-pane content start (was {wrapped_start}, expected >= {right_start})"
        );

        let added_bg = ctx.theme.diff_added_bg();
        let removed_bg = ctx.theme.diff_removed_bg();
        let gutter_width = gutter_width_for_preview(&preview);
        let padding_width = gutter_width + SEPARATOR_WIDTH;
        assert!(right_start >= padding_width, "right pane content should leave room for separator and gutter");
        for col in (right_start - padding_width)..right_start {
            let style = style_at_column(&lines[wrapped_row], col);
            assert_ne!(style.bg, Some(added_bg), "padding column {col} should not inherit added background");
            assert_ne!(style.bg, Some(removed_bg), "padding column {col} should not inherit removed background");
        }
    }

    #[test]
    fn both_panels_rendered_with_content() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell("old code", 1)),
            right: Some(added_cell("new code", 1)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert_eq!(lines.len(), 1);
        let text = lines[0].plain_text();
        assert!(text.contains("old code"), "left panel missing: {text}");
        assert!(text.contains("new code"), "right panel missing: {text}");
    }

    #[test]
    fn long_lines_wrapped_within_terminal_width() {
        let long = "x".repeat(200);
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell(&long, 1)),
            right: Some(added_cell(&long, 1)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert!(lines.len() > 1, "long line should wrap into multiple visual lines, got {}", lines.len());
        for line in &lines {
            let width = line.display_width();
            assert!(width <= 100, "line width {width} should not exceed terminal width 100");
        }
        // Full content should be present across all wrapped lines
        let all_text: String = lines.iter().map(Line::plain_text).collect();
        let x_count = all_text.chars().filter(|&c| c == 'x').count();
        // Both left and right panels contain 200 x's each
        assert_eq!(x_count, 400, "all content should be present across wrapped lines");
    }

    #[test]
    fn truncation_budget_applied() {
        let rows: Vec<SplitDiffRow> = (0..30)
            .map(|i| SplitDiffRow {
                left: Some(removed_cell(&format!("old {i}"), i + 1)),
                right: Some(added_cell(&format!("new {i}"), i + 1)),
            })
            .collect();
        let preview = make_split_preview(rows);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        // Short lines don't wrap, so 20 visual lines + 1 overflow
        assert_eq!(lines.len(), MAX_DIFF_LINES + 1);
        let last = lines.last().unwrap().plain_text();
        assert!(last.contains("more lines"), "overflow text missing: {last}");
    }

    #[test]
    fn empty_added_cell_pads_content_with_added_background() {
        let ctx = test_context_with_width(100);
        let added_bg = ctx.theme.diff_added_bg();
        let cell = SplitDiffCell { tag: DiffTag::Added, content: String::new(), line_number: Some(1) };
        let content_width = 40;
        let gutter_width = MIN_GUTTER_WIDTH;
        let frame = render_cell(Some(&cell), content_width, "rs", Side::Right, gutter_width, &ctx);
        let lines = frame.into_lines();
        assert_eq!(lines.len(), 1);
        let row = &lines[0];
        assert_eq!(
            row.display_width(),
            gutter_width + content_width,
            "row should fill panel width, got {}",
            row.display_width()
        );
        let trailing = row.spans().last().expect("row should have spans");
        assert_eq!(
            trailing.style().bg,
            Some(added_bg),
            "trailing pad of empty added cell should carry diff_added_bg, got {:?}",
            trailing.style().bg
        );
    }

    #[test]
    fn empty_preview_produces_no_output() {
        let preview = make_split_preview(vec![]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert!(lines.is_empty());
    }

    #[test]
    fn render_diff_dispatches_to_unified_below_80() {
        let preview = DiffPreview {
            lines: vec![DiffLine { tag: DiffTag::Removed, content: "old".to_string() }],
            rows: vec![SplitDiffRow { left: Some(removed_cell("old", 1)), right: None }],
            lang_hint: String::new(),
            start_line: None,
        };
        let ctx = test_context_with_width(79);
        let lines = render_diff(&preview, &ctx);
        // Unified renderer uses prefix "  - "
        assert!(
            lines[0].plain_text().contains("- old"),
            "should use unified renderer below 80: {}",
            lines[0].plain_text()
        );
    }

    #[test]
    fn new_file_uses_unified_view_even_at_wide_width() {
        // A new file (only additions, no removals) should use unified view
        // since split view would have an empty left panel
        let preview = DiffPreview {
            lines: vec![
                DiffLine { tag: DiffTag::Added, content: "fn main() {".to_string() },
                DiffLine { tag: DiffTag::Added, content: "    println!(\"Hello\");".to_string() },
                DiffLine { tag: DiffTag::Added, content: "}".to_string() },
            ],
            rows: vec![
                SplitDiffRow { left: None, right: Some(added_cell("fn main() {", 1)) },
                SplitDiffRow { left: None, right: Some(added_cell("    println!(\"Hello\");", 2)) },
                SplitDiffRow { left: None, right: Some(added_cell("}", 3)) },
            ],
            lang_hint: "rs".to_string(),
            start_line: None,
        };
        let ctx = test_context_with_width(100);
        let lines = render_diff(&preview, &ctx);
        // Unified renderer uses prefix "  + "
        let text = lines[0].plain_text();
        assert!(text.contains("+ fn main()"), "should use unified renderer for new file: {text}");
    }

    #[test]
    fn render_diff_dispatches_to_split_at_80() {
        let preview = DiffPreview {
            lines: vec![DiffLine { tag: DiffTag::Removed, content: "old".to_string() }],
            rows: vec![SplitDiffRow { left: Some(removed_cell("old", 1)), right: None }],
            lang_hint: String::new(),
            start_line: None,
        };
        let ctx = test_context_with_width(80);
        let lines = render_diff(&preview, &ctx);
        let text = lines[0].plain_text();
        // Split renderer shows line number gutter, not unified "- " prefix
        assert!(!text.contains("- old"), "should use split renderer at 80: {text}");
    }

    #[test]
    fn line_numbers_rendered_when_start_line_set() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(SplitDiffCell { tag: DiffTag::Context, content: "hello".to_string(), line_number: Some(42) }),
            right: Some(SplitDiffCell { tag: DiffTag::Context, content: "hello".to_string(), line_number: Some(42) }),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        let text = lines[0].plain_text();
        assert!(text.contains("42"), "line number should be shown: {text}");
    }

    #[test]
    fn wrapped_row_pads_shorter_side_to_match_height() {
        // Left side has a long line that wraps, right side is short
        let long = "a".repeat(200);
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell(&long, 1)),
            right: Some(added_cell("short", 1)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert!(lines.len() > 1, "long left side should produce multiple visual lines");
        // All lines should have consistent width
        let first_width = lines[0].display_width();
        for (i, line) in lines.iter().enumerate() {
            assert_eq!(line.display_width(), first_width, "line {i} width mismatch");
        }
    }

    #[test]
    fn separator_has_no_background_on_context_row() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(SplitDiffCell { tag: DiffTag::Context, content: "hello".to_string(), line_number: Some(1) }),
            right: Some(SplitDiffCell { tag: DiffTag::Context, content: "world".to_string(), line_number: Some(1) }),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert_eq!(lines.len(), 1);

        let gutter_width = gutter_width_for_preview(&preview);
        let usable = 100usize - (gutter_width * 2 + SEPARATOR_WIDTH + LEFT_INNER_PAD);
        let left_content = usable / 2;
        let sep_start = gutter_width + left_content + LEFT_INNER_PAD;
        let sep_end = sep_start + SEPARATOR_WIDTH;
        for col in sep_start..sep_end {
            let style = style_at_column(&lines[0], col);
            assert!(
                style.bg.is_none(),
                "separator column {col} should have no background on context row, got {:?}",
                style.bg
            );
        }
    }

    #[test]
    fn blank_gutter_when_line_number_none() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(SplitDiffCell { tag: DiffTag::Removed, content: "old".to_string(), line_number: None }),
            right: None,
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        let text = lines[0].plain_text();
        let blank_gutter = " ".repeat(gutter_width_for_preview(&preview));
        assert!(text.starts_with(&blank_gutter), "should have blank gutter: {text:?}");
    }

    #[test]
    fn left_pane_diff_bg_extends_through_inner_pad_to_separator() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell("old", 1)),
            right: Some(added_cell("new", 1)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert_eq!(lines.len(), 1);

        let gutter_width = gutter_width_for_preview(&preview);
        let usable = 100usize - (gutter_width * 2 + SEPARATOR_WIDTH + LEFT_INNER_PAD);
        let left_content = usable / 2;
        let inner_pad_col = gutter_width + left_content + LEFT_INNER_PAD - 1;
        let style = style_at_column(&lines[0], inner_pad_col);
        assert_eq!(
            style.bg,
            Some(ctx.theme.diff_removed_bg()),
            "left inner-edge pad column {inner_pad_col} should carry diff_removed_bg, got {:?}",
            style.bg,
        );
    }

    #[test]
    fn right_pane_line_number_sits_adjacent_to_separator() {
        let preview = make_split_preview(vec![SplitDiffRow {
            left: Some(removed_cell("old", 89)),
            right: Some(added_cell("new", 89)),
        }]);
        let ctx = test_context_with_width(100);
        let lines = highlight_split_diff(&preview, &ctx);
        assert_eq!(lines.len(), 1);

        let gutter_width = gutter_width_for_preview(&preview);
        let usable = 100usize - (gutter_width * 2 + SEPARATOR_WIDTH + LEFT_INNER_PAD);
        let left_content = usable / 2;
        let right_pane_first_col = gutter_width + left_content + LEFT_INNER_PAD + SEPARATOR_WIDTH;
        let text = lines[0].plain_text();
        let chars: Vec<char> = text.chars().collect();
        assert_eq!(
            chars[right_pane_first_col], '8',
            "right pane line# digit '8' should sit at the very first column after SEP (col {right_pane_first_col}); got line: {text:?}",
        );
        assert_eq!(
            chars[right_pane_first_col + 1],
            '9',
            "right pane line# digit '9' should follow at col {}",
            right_pane_first_col + 1
        );
    }
}