gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
use ratatui::{
    layout::{Constraint, Layout, Rect},
    style::Style,
    text::{Line, Span},
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::theme;
use crate::app::App;

// =============================================================================
// Unicode width helper functions
// =============================================================================

/// Calculate the display width of a string (CJK characters are width 2, ASCII characters are width 1)
pub(crate) fn display_width(s: &str) -> usize {
    UnicodeWidthStr::width(s)
}

/// Truncate a string to the specified display width
pub(crate) fn truncate_to_width(s: &str, max_width: usize) -> String {
    let mut width = 0;
    let mut result = String::new();
    for c in s.chars() {
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if width + w > max_width {
            break;
        }
        result.push(c);
        width += w;
    }
    result
}

/// Skip the specified display width from the beginning of a string and return the rest
pub(crate) fn skip_width(s: &str, skip: usize) -> String {
    if skip == 0 {
        return s.to_string();
    }
    let mut width = 0;
    let mut byte_offset = 0;
    for c in s.chars() {
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if width + w > skip {
            break;
        }
        width += w;
        byte_offset += c.len_utf8();
        if width >= skip {
            break;
        }
    }
    s[byte_offset..].to_string()
}

/// Truncate a string to the specified display width and append an ellipsis
pub(crate) fn truncate_to_width_with_ellipsis(s: &str, max_width: usize) -> String {
    let s_width = display_width(s);
    if s_width <= max_width {
        return s.to_string();
    }
    if max_width <= 3 {
        return truncate_to_width(s, max_width);
    }
    let truncated = truncate_to_width(s, max_width.saturating_sub(3));
    format!("{}...", truncated)
}

/// Truncate a single line to the specified width while preserving Span styles
pub(crate) fn truncate_line_to_width(line: &Line, max_width: usize) -> Line<'static> {
    if max_width == 0 {
        return Line::from("");
    }

    let mut remaining = max_width;
    let mut spans = Vec::new();

    for span in &line.spans {
        if remaining == 0 {
            break;
        }
        let text = span.content.as_ref();
        let text_width = display_width(text);
        if text_width <= remaining {
            spans.push(Span::styled(text.to_string(), span.style));
            remaining = remaining.saturating_sub(text_width);
            continue;
        }

        let mut out = String::new();
        let mut used = 0usize;
        for ch in text.chars() {
            let w = UnicodeWidthChar::width(ch).unwrap_or(0);
            if used + w > remaining {
                break;
            }
            out.push(ch);
            used += w;
        }
        if !out.is_empty() {
            spans.push(Span::styled(out, span.style));
        }
        break;
    }

    Line::from(spans)
}

/// Adjust a list of lines to fit within the display area
pub(crate) fn fit_lines_to_inner_area(
    lines: Vec<Line<'static>>,
    inner_width: usize,
    inner_height: usize,
) -> Vec<Line<'static>> {
    lines
        .into_iter()
        .take(inner_height)
        .map(|line| truncate_line_to_width(&line, inner_width))
        .collect()
}

/// Clamp the desired size to fit within the screen and center it
pub(crate) fn centered_overlay_rect(area: Rect, desired_width: u16, desired_height: u16) -> Rect {
    let width = desired_width.max(1).min(area.width.max(1));
    let height = desired_height.max(1).min(area.height.max(1));
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    Rect::new(x, y, width, height)
}

// =============================================================================
// Layout constants
// =============================================================================

/// Footer height
pub(crate) const FOOTER_HEIGHT: u16 = 3;

// =============================================================================
// Overlay constants
// =============================================================================

/// Overlay background color
pub(crate) const OVERLAY_BG_COLOR: ratatui::style::Color = theme::SURFACE0;

/// Overlay minimum width (supports 30-character width)
pub(crate) const OVERLAY_MIN_WIDTH: u16 = 24;

/// Overlay margin from screen edges (smaller on narrow screens)
pub(crate) const OVERLAY_MARGIN: u16 = 2;

/// Detail overlay height (enlarged to display file list)
pub(crate) const DETAIL_OVERLAY_HEIGHT: u16 = 20;

/// Branch selection minimum width
pub(crate) const BRANCH_OVERLAY_MIN_WIDTH: u16 = 20;

/// Branch selection padding (prefix + whitespace)
pub(crate) const BRANCH_OVERLAY_PADDING: u16 = 6;

/// Status display minimum path length (supports 30-character width)
pub(crate) const STATUS_MIN_PATH_LEN: usize = 15;

/// Status display padding
pub(crate) const STATUS_OVERLAY_PADDING: u16 = 12;

/// Overlay border height (top and bottom)
pub(crate) const OVERLAY_BORDER_HEIGHT: u16 = 2;

/// Overlay minimum height
pub(crate) const OVERLAY_MIN_HEIGHT: u16 = 4;

/// Overlay width (standard 80%)
pub(crate) const OVERLAY_WIDTH_PERCENT_STANDARD: u16 = 80;

/// Overlay height (standard 80%)
const OVERLAY_HEIGHT_PERCENT_STANDARD: u16 = 80;

/// Overlay border width (left and right)
const OVERLAY_BORDER_WIDTH: u16 = 2;

/// Calculate standard overlay size (80% width)
pub(crate) fn compute_overlay_size_standard(area: Rect) -> (u16, u16, u16, u16) {
    let width = (area.width * OVERLAY_WIDTH_PERCENT_STANDARD / 100)
        .max(OVERLAY_MIN_WIDTH)
        .min(area.width.saturating_sub(4));
    let height =
        (area.height * OVERLAY_HEIGHT_PERCENT_STANDARD / 100).min(area.height.saturating_sub(4));
    let x = (area.width.saturating_sub(width)) / 2;
    let y = (area.height.saturating_sub(height)) / 2;
    (x, y, width, height)
}

// =============================================================================
// Icon constants
// =============================================================================

/// Branch selection marker (selected)
pub(crate) const BRANCH_MARKER_SELECTED: &str = "";

/// Branch selection marker (unselected)
pub(crate) const BRANCH_MARKER_UNSELECTED: &str = "  ";

/// Current branch marker
pub(crate) const CURRENT_BRANCH_MARKER: &str = "";

/// Non-current branch placeholder
pub(crate) const NOT_CURRENT_BRANCH_MARKER: &str = "  ";

// =============================================================================
// Helper functions
// =============================================================================

/// Layout areas
pub struct LayoutAreas {
    pub footer: Rect,
    /// Sidebar panel areas (Status, Commits, Branches, Files, Stash)
    pub sidebar_panels: [Rect; 5],
    /// Main panel area
    pub dashboard_main: Rect,
}

/// Calculate dashboard layout
pub fn calculate_layout_areas(area: Rect, app: &App) -> LayoutAreas {
    let [main_area, footer] =
        Layout::vertical([Constraint::Min(0), Constraint::Length(FOOTER_HEIGHT)]).areas(area);

    let sidebar_ratio = app.sidebar_width_ratio as u32;
    let sidebar_width = (main_area.width as u32 * sidebar_ratio / 100) as u16;
    let sidebar_width = sidebar_width.max(20).min(main_area.width / 2);
    let main_width = main_area.width.saturating_sub(sidebar_width);

    let [sidebar_area, dashboard_main_area] = Layout::horizontal([
        Constraint::Length(sidebar_width),
        Constraint::Length(main_width),
    ])
    .areas(main_area);

    // Split sidebar into 5 panels
    // Status: fixed 3 lines, remaining split as Commits(40%), Branches(20%), Files(25%), Stash(15%)
    let remaining_height = sidebar_area.height.saturating_sub(3);
    let commits_h = (remaining_height as u32 * 40 / 100) as u16;
    let branches_h = (remaining_height as u32 * 20 / 100) as u16;
    let files_h = (remaining_height as u32 * 25 / 100) as u16;
    let stash_h = remaining_height.saturating_sub(commits_h + branches_h + files_h);

    let [status_area, commits_area, branches_area, files_area, stash_area] = Layout::vertical([
        Constraint::Length(3),
        Constraint::Length(commits_h),
        Constraint::Length(branches_h),
        Constraint::Length(files_h),
        Constraint::Length(stash_h),
    ])
    .areas(sidebar_area);

    LayoutAreas {
        footer,
        sidebar_panels: [
            status_area,
            commits_area,
            branches_area,
            files_area,
            stash_area,
        ],
        dashboard_main: dashboard_main_area,
    }
}

/// Pre-computed overlay layout context to eliminate boilerplate in render functions.
///
/// Replaces the repeated pattern of:
/// ```ignore
/// let area = frame.area();
/// let overlay_width = ((area.width as f32 * ratio) as u16).max(MIN).min(MAX);
/// let overlay_height = (area.height as f32 * ratio) as u16;
/// let x = (area.width.saturating_sub(overlay_width)) / 2;
/// let y = (area.height.saturating_sub(overlay_height)) / 2;
/// let overlay_area = Rect::new(x, y, overlay_width, overlay_height);
/// let inner_width = overlay_width.saturating_sub(2) as usize;
/// frame.render_widget(Clear, overlay_area);
/// ```
pub(crate) struct OverlayContext {
    /// The overlay area (position + size), centered on screen
    pub area: Rect,
    /// Usable width inside the border (overlay_width - 2)
    pub inner_width: usize,
}

impl OverlayContext {
    /// Standard overlay: 80% width × 80% height, centered
    pub fn standard(frame: &ratatui::Frame) -> Self {
        let screen = frame.area();
        let (x, y, width, height) = compute_overlay_size_standard(screen);
        let area = Rect::new(x, y, width, height);
        let inner_width = width.saturating_sub(OVERLAY_BORDER_WIDTH) as usize;
        // We cannot render here because we only have &Frame, not &mut Frame.
        // The caller must call `ctx.clear(frame)` separately.
        Self { area, inner_width }
    }

    /// Custom overlay with explicit dimensions
    pub fn custom(frame: &ratatui::Frame, width: u16, height: u16) -> Self {
        let screen = frame.area();
        let w = width
            .max(OVERLAY_MIN_WIDTH)
            .min(screen.width.saturating_sub(OVERLAY_MARGIN * 2));
        let h = height.min(screen.height.saturating_sub(OVERLAY_MARGIN * 2));
        let x = (screen.width.saturating_sub(w)) / 2;
        let y = (screen.height.saturating_sub(h)) / 2;
        let area = Rect::new(x, y, w, h);
        let inner_width = w.saturating_sub(OVERLAY_BORDER_WIDTH) as usize;
        Self { area, inner_width }
    }

    /// Clear the overlay area and return the area for rendering
    pub fn clear(&self, frame: &mut ratatui::Frame) -> Rect {
        frame.render_widget(ratatui::widgets::Clear, self.area);
        self.area
    }
}

/// Generate a score bar (format: ████░░)
pub(crate) fn score_bar_spans(ratio: f64, width: usize) -> Vec<Span<'static>> {
    let filled = (ratio * width as f64).round() as usize;
    let empty = width.saturating_sub(filled);
    let pct = (ratio * 100.0).round() as u8;
    let color = match pct {
        80..=100 => theme::GREEN,
        60..=79 => theme::TEAL,
        40..=59 => theme::YELLOW,
        20..=39 => theme::PEACH,
        _ => theme::RED,
    };
    vec![
        Span::styled("\u{2588}".repeat(filled), Style::default().fg(color)),
        Span::styled(
            "\u{2591}".repeat(empty),
            Style::default().fg(theme::OVERLAY0),
        ),
    ]
}

/// Generate a separator line
pub(crate) fn detail_separator_line(width: u16) -> Line<'static> {
    Line::from(Span::styled(
        "\u{2500}".repeat(width.saturating_sub(2) as usize),
        Style::default().fg(theme::OVERLAY0),
    ))
}

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

    #[test]
    fn test_centered_overlay_rect_clamps_to_area() {
        let area = Rect::new(0, 0, 20, 6);
        let rect = centered_overlay_rect(area, 50, 20);
        assert_eq!(rect.width, 20);
        assert_eq!(rect.height, 6);
    }

    #[test]
    fn test_fit_lines_to_inner_area_truncates_and_limits_height() {
        let lines = vec![
            Line::from("123456789"),
            Line::from("abcdefghi"),
            Line::from("zzzzzzzzz"),
        ];
        let fitted = fit_lines_to_inner_area(lines, 5, 2);
        assert_eq!(fitted.len(), 2);
        assert_eq!(display_width(fitted[0].spans[0].content.as_ref()), 5);
        assert_eq!(display_width(fitted[1].spans[0].content.as_ref()), 5);
    }

    // =============================================================================
    // Unicode width helper function tests
    // =============================================================================

    #[test]
    fn test_display_width_ascii() {
        assert_eq!(display_width("hello"), 5);
        assert_eq!(display_width("abc123"), 6);
    }

    #[test]
    fn test_display_width_cjk() {
        // Japanese characters are full-width (2 columns each)
        assert_eq!(display_width("日本語"), 6);
        assert_eq!(display_width("こんにちは"), 10);
    }

    #[test]
    fn test_display_width_mixed() {
        // Mixed: ASCII(1) + Japanese(2)
        assert_eq!(display_width("Hello世界"), 9); // 5 + 2*2
        assert_eq!(display_width("abc日本語def"), 12); // 3 + 6 + 3
    }

    #[test]
    fn test_truncate_to_width_ascii() {
        assert_eq!(truncate_to_width("hello world", 5), "hello");
        assert_eq!(truncate_to_width("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_to_width_cjk() {
        // Truncate Japanese by width
        assert_eq!(truncate_to_width("日本語テスト", 6), "日本語");
        assert_eq!(truncate_to_width("こんにちは", 4), "こん");
    }

    #[test]
    fn test_truncate_to_width_mixed() {
        // Truncate mixed text
        assert_eq!(truncate_to_width("Hello世界", 7), "Hello世"); // 5 + 2
        assert_eq!(truncate_to_width("abc日本語", 5), "abc日"); // 3 + 2
    }

    #[test]
    fn test_truncate_to_width_boundary() {
        // Boundary case: width falls in the middle of a character
        assert_eq!(truncate_to_width("日本語", 3), ""); // 2nd character doesn't fit
        assert_eq!(truncate_to_width("日本語", 5), "日本"); // 3rd character doesn't fit
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_no_truncation() {
        // No truncation needed
        assert_eq!(truncate_to_width_with_ellipsis("short", 10), "short");
        assert_eq!(truncate_to_width_with_ellipsis("日本語", 10), "日本語");
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_ascii() {
        assert_eq!(
            truncate_to_width_with_ellipsis("hello world", 8),
            "hello..."
        );
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_cjk() {
        // Japanese + "..." should not exceed total width
        assert_eq!(
            truncate_to_width_with_ellipsis("日本語テスト", 9),
            "日本語..."
        ); // 6 + 3
        assert_eq!(
            truncate_to_width_with_ellipsis("こんにちは世界", 9),
            "こんに..."
        ); // 6 + 3
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_small_width() {
        // No ellipsis when width is too small
        assert_eq!(truncate_to_width_with_ellipsis("hello", 3), "hel");
        assert_eq!(truncate_to_width_with_ellipsis("日本語", 2), "");
    }

    #[test]
    fn test_display_width_empty() {
        assert_eq!(display_width(""), 0);
    }

    #[test]
    fn test_truncate_to_width_empty() {
        assert_eq!(truncate_to_width("", 10), "");
        assert_eq!(truncate_to_width("hello", 0), "");
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_empty() {
        assert_eq!(truncate_to_width_with_ellipsis("", 10), "");
        assert_eq!(truncate_to_width_with_ellipsis("hello", 0), "");
    }

    #[test]
    fn test_truncate_to_width_with_ellipsis_exact_fit() {
        // No ellipsis when it fits exactly
        assert_eq!(truncate_to_width_with_ellipsis("hello", 5), "hello");
        assert_eq!(truncate_to_width_with_ellipsis("日本語", 6), "日本語");
    }

    // ===== LayoutAreas-related tests =====

    #[test]
    fn test_calculate_layout_areas_dashboard() {
        let app = App::new();
        let area = Rect::new(0, 0, 150, 30);
        let layout = calculate_layout_areas(area, &app);

        assert_eq!(layout.sidebar_panels.len(), 5);
        assert!(layout.dashboard_main.width > 0);
        assert_eq!(layout.footer.height, FOOTER_HEIGHT);
    }

    // ===== OverlayContext (compute_overlay_size_standard) tests =====

    #[test]
    fn test_overlay_standard_size_centered() {
        let area = Rect::new(0, 0, 100, 50);
        let (x, y, w, h) = compute_overlay_size_standard(area);
        assert_eq!(w, 80); // 80% of 100
        assert_eq!(h, 40); // 80% of 50
        assert_eq!(x, 10); // centered
        assert_eq!(y, 5); // centered
    }

    #[test]
    fn test_overlay_standard_size_small_terminal() {
        let area = Rect::new(0, 0, 40, 20);
        let (x, y, w, h) = compute_overlay_size_standard(area);
        // width = max(40*80/100=32, OVERLAY_MIN_WIDTH=30) = 32, min(32, 40-4=36) = 32
        assert!(w >= OVERLAY_MIN_WIDTH);
        assert!(w <= area.width);
        assert!(h <= area.height);
        // centered
        assert_eq!(x, (area.width - w) / 2);
        assert_eq!(y, (area.height - h) / 2);
    }

    #[test]
    fn test_overlay_standard_min_width_enforced() {
        // OVERLAY_MIN_WIDTH = 24. Use terminal width where 80% < 24
        let area = Rect::new(0, 0, 28, 20);
        let (_x, _y, w, _h) = compute_overlay_size_standard(area);
        // 28*80/100 = 22 < 24, so max(22, 24) = 24, min(24, 28-4=24) = 24
        assert_eq!(w, OVERLAY_MIN_WIDTH);
    }

    #[test]
    fn test_overlay_standard_very_small_terminal() {
        let area = Rect::new(0, 0, 20, 10);
        let (x, y, w, h) = compute_overlay_size_standard(area);
        // max(16, 30) = 30, min(30, 16) = 16
        assert!(w <= area.width);
        assert!(h <= area.height);
        assert!(x + w <= area.width);
        assert!(y + h <= area.height);
    }
}