crates/brain/src/session/status.rs 37.3 KiB raw
1
//! Status and chrome rendering for the review session.
2
3
use std::cmp::Ordering;
4
use std::time::{SystemTime, UNIX_EPOCH};
5
6
use rustik_diff::{
7
    DiffPalette, ReviewProgress, diffstat, file_count, progress_bar, recoverable_error,
8
};
9
use rustik_repo::DiffStat;
10
use rustik_tui::{
11
    Border, Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Table, TableOptions,
12
    Widget, colors,
13
};
14
15
use crate::backend::CommitReviewState;
16
use crate::comments::{COMMENT_MARK, Comment};
17
use crate::review::{FileVisibility, HunkVisibility, Visibility};
18
19
use super::commit::CommitSlot;
20
21
/// Number of rows used by the status bar.
22
const STATUS_ROWS: usize = 1;
23
/// Number of rows used by the action bar.
24
const ACTION_ROWS: usize = 1;
25
/// Number of rows reserved for the bottom footer when possible.
26
const CHROME_ROWS: usize = STATUS_ROWS + ACTION_ROWS;
27
/// Empty columns between status content and the status bar's right edge.
28
const STATUS_RIGHT_PADDING: usize = 1;
29
/// Maximum width of a history diffstat graph.
30
pub(super) const HISTORY_DIFFSTAT_MAX_WIDTH: usize = 32;
31
/// Columns reserved for the total hunk count in commit history.
32
const HISTORY_HUNK_COUNT_WIDTH: usize = 4;
33
/// Foreground color for dim footer text.
34
const FOOTER_FG: Color = Color::Fixed(240);
35
/// Foreground color for prominent history values.
36
const HISTORY_VALUE_FG: Color = Color::Fixed(246);
37
/// Background color for the footer row, matching file border chrome.
38
const FOOTER_BG: Color = colors::FAINT;
39
/// Background color for the brain application badge.
40
pub(crate) const BRAIN_BADGE_BG: Color = Color::RGB(124, 36, 32);
41
/// Background color for the active-mode badge.
42
const MODE_BADGE_BG: Color = Color::RGB(68, 68, 68);
43
/// Foreground color for the current commit hash.
44
const FOOTER_HASH_FG: Color = Color::Fixed(250);
45
/// Foreground color for neutral footer values.
46
const FOOTER_VALUE_FG: Color = FOOTER_HASH_FG;
47
/// Foreground color for the current commit summary.
48
const FOOTER_SUMMARY_FG: Color = Color::Fixed(153);
49
/// Border color for the selected comment in the hunk view.
50
const SELECTED_COMMENT_BORDER: Color = Color::Fixed(239);
51
/// Background color for the selected commit, matching the active file row.
52
pub(super) const SELECTED_COMMIT_BG: Color = Color::Fixed(235);
53
/// Marker shown beside a commit whose hunks have all been accepted: ✔.
54
const REVIEWED_MARK: char = '✔';
55
/// Marker shown beside a rejected commit: ✗.
56
const REJECTED_MARK: char = '✗';
57
/// Marker shown beside a dropped commit.
58
const DROPPED_MARK: char = '-';
59
/// Marker shown beside a commit that has not been reviewed.
60
const PENDING_MARK: char = '○';
61
/// Marker shown beside a commit whose review is in progress.
62
const IN_PROGRESS_MARK: char = '◐';
63
/// Marker highlighted when all hunks are visible in the footer: ✔.
64
const ALL_HUNKS_MODE_ICON: &str = "✔";
65
/// Marker shown when full-file mode is visible in the footer: ↕.
66
const FULL_FILE_MODE_ICON: &str = "↕";
67
/// Separator shown between footer status segments: ·.
68
const FOOTER_SEPARATOR: &str = " · ";
69
/// Marker used when footer text truncates: ….
70
const FOOTER_ELLIPSIS: &str = "…";
71
/// Frames used by the repository-operation status spinner.
72
const SPINNER_FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
73
/// Separator shown between plain action hints.
74
const ACTION_SEPARATOR: &str = " · ";
75
/// Key label shown for Tab: ⭾.
76
const TAB_KEY: &str = "⭾";
77
/// Key label shown for Return: ⮐.
78
const RETURN_KEY: &str = "⮐";
79
/// Key label shown for Ctrl-Return.
80
const CTRL_RETURN_KEY: &str = "ctrl-⮐";
81
/// Foreground color for contextual action labels.
82
const ACTION_LABEL_FG: Color = Color::Fixed(244);
83
/// Foreground color for contextual action keys.
84
const ACTION_KEY_FG: Color = Color::Fixed(250);
85
/// Foreground color for active context-expansion mode.
86
const FULL_FILE_MODE_FG: Color = colors::rgb::TEAL;
87
/// Action hints shown in commit-list mode.
88
const COMMITS_ACTIONS: &[(&str, &str)] = &[
89
    (TAB_KEY, "commit"),
90
    ("j/k", "select"),
91
    (RETURN_KEY, "open"),
92
    ("r", "reject commit"),
93
    ("d", "drop commit"),
94
    ("q", "quit"),
95
];
96
/// Action hints shown in commit diff mode.
97
const COMMIT_ACTIONS: &[(&str, &str)] = &[
98
    (TAB_KEY, "history"),
99
    ("q", "quit"),
100
    ("j/k", "hunk"),
101
    ("n/p", "file"),
102
    ("a", "accept hunk"),
103
    ("r", "reject commit"),
104
    ("d", "drop commit"),
105
    ("u", "undo"),
106
    ("c", "comment"),
107
];
108
/// Action hints shown while browsing hunk comments.
109
const HUNK_BROWSE_ACTIONS: &[(&str, &str)] = &[
110
    (TAB_KEY, "history"),
111
    ("r", "reject commit"),
112
    ("c", "new"),
113
    ("e", "edit"),
114
    ("d", "delete"),
115
    ("n/p", "select"),
116
    ("esc", "commit"),
117
];
118
/// Action hints shown while editing a hunk comment.
119
const HUNK_EDIT_ACTIONS: &[(&str, &str)] = &[
120
    (RETURN_KEY, "newline"),
121
    (CTRL_RETURN_KEY, "save"),
122
    ("esc", "cancel"),
123
    (TAB_KEY, "history"),
124
];
125
/// Rows of card chrome around a comment body: the top border, the header row,
126
/// and the bottom border.
127
pub(super) const COMMENT_CARD_CHROME_ROWS: usize = 3;
128
/// Columns of card chrome on each side of a comment body: the border and its
129
/// padding.
130
pub(super) const COMMENT_CARD_CHROME_COLS: usize = 2;
131
132
/// Context shown on the left side of the footer status.
133
#[derive(Debug)]
134
pub(super) enum StatusContext {
135
    /// Selected commit identity and summary.
136
    Commit {
137
        /// Abbreviated commit hash.
138
        short: String,
139
        /// First line of the commit message.
140
        summary: String,
141
        /// Final review decision for this commit.
142
        state: CommitReviewState,
143
    },
144
    /// Reviewed revision range.
145
    Range(String),
146
}
147
148
/// Footer status describing the current review context and progress.
149
#[derive(Debug)]
150
pub(super) struct Status {
151
    /// Active review mode name.
152
    pub(super) mode: &'static str,
153
    /// Review context displayed for the active mode.
154
    pub(super) context: StatusContext,
155
    /// Accepted-line progress for the active review context.
156
    pub(super) progress: ReviewProgress,
157
    /// Aggregated diff size for the active review context.
158
    pub(super) stats: DiffStat,
159
    /// Diff palette used for stat and review colors.
160
    pub(super) palette: DiffPalette,
161
    /// Visibility modes for the active review view.
162
    pub(super) visibility: Visibility,
163
    /// Most recent recoverable session error.
164
    pub(super) error: Option<String>,
165
    /// Active repository operation and animation frame.
166
    pub(super) loading: Option<(&'static str, usize)>,
167
}
168
169
impl Widget for Status {
170
    fn size(&self, parent: Constraint) -> Size {
171
        Size::new(parent.max.cols, STATUS_ROWS).constrain(parent)
172
    }
173
174
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
175
        if area.is_empty() {
176
            return;
177
        }
178
        Self::background(area.cols).render(area, buf);
179
        self.bar(area.cols).render(area, buf);
180
    }
181
}
182
183
impl Status {
184
    /// Returns the full-width status row background.
185
    fn background(cols: usize) -> Line {
186
        Line::new(Label::space().bg(FOOTER_BG)).padded(cols)
187
    }
188
189
    /// Returns the bottom status row content.
190
    fn bar(&self, cols: usize) -> HStack<'_> {
191
        if let Some(error) = &self.error {
192
            return HStack::default()
193
                .child(recoverable_error(error, FOOTER_VALUE_FG, FOOTER_BG).truncated(cols, ""));
194
        }
195
        if self.loading.is_some() {
196
            return HStack::default().child(self.left_status().truncated(cols, FOOTER_ELLIPSIS));
197
        }
198
        let right = self.right_status();
199
        let left_width = cols
200
            .saturating_sub(right.width())
201
            .saturating_sub(STATUS_RIGHT_PADDING)
202
            .saturating_sub(1);
203
204
        HStack::default()
205
            .child(self.left_status().truncated(left_width, FOOTER_ELLIPSIS))
206
            .spacer()
207
            .child(right)
208
            .child(Line::new(Label::space().bg(FOOTER_BG)).padded(STATUS_RIGHT_PADDING))
209
    }
210
211
    /// Returns the left status section with application, mode, and review context.
212
    fn left_status(&self) -> Line {
213
        let context = if let Some((operation, frame)) = self.loading {
214
            let spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.len()];
215
            Line::new(Label::from_char(spinner).fg(FOOTER_VALUE_FG))
216
                .item(Label::space())
217
                .item(Label::new(operation).fg(FOOTER_VALUE_FG))
218
        } else {
219
            match &self.context {
220
                StatusContext::Commit {
221
                    short,
222
                    summary,
223
                    state,
224
                } => {
225
                    let (marker, color) = match state {
226
                        CommitReviewState::Accepted => (REVIEWED_MARK, self.palette.positive_fg),
227
                        CommitReviewState::Rejected => (REJECTED_MARK, self.palette.negative_fg),
228
                        CommitReviewState::Dropped => (DROPPED_MARK, colors::fixed::MUTED),
229
                        CommitReviewState::Pending => (PENDING_MARK, colors::fixed::MUTED),
230
                    };
231
                    Line::new(Label::from_char(marker).fg(color))
232
                        .item(Label::space())
233
                        .item(Label::new(short).fg(FOOTER_HASH_FG))
234
                        .item(Label::space())
235
                        .item(Label::new(summary).fg(FOOTER_SUMMARY_FG))
236
                }
237
                StatusContext::Range(range) => Line::new(Label::new(range).fg(FOOTER_SUMMARY_FG)),
238
            }
239
        };
240
        Line::blank()
241
            .item(
242
                Label::new(" brain ")
243
                    .fg(Color::White)
244
                    .bg(BRAIN_BADGE_BG)
245
                    .style(Style::default().bold()),
246
            )
247
            .item(
248
                Label::new(&format!(" {} ", self.mode))
249
                    .fg(Color::White)
250
                    .bg(MODE_BADGE_BG)
251
                    .style(Style::default().bold()),
252
            )
253
            .item(Label::space())
254
            .extend(context)
255
            .style(Style::default().bg(FOOTER_BG))
256
    }
257
258
    /// Returns the right status section with review state and diff statistics.
259
    fn right_status(&self) -> Line {
260
        let all_hunks_fg = match self.visibility.hunks {
261
            HunkVisibility::Pending => FOOTER_FG,
262
            HunkVisibility::All => self.palette.positive_fg,
263
        };
264
        let full_file_fg = match self.visibility.file {
265
            FileVisibility::Context => FOOTER_FG,
266
            FileVisibility::Full => FULL_FILE_MODE_FG,
267
        };
268
        let mut status = Line::blank().extend(progress_bar(self.progress, self.palette, FOOTER_FG));
269
        if !matches!(self.context, StatusContext::Commit { .. }) || !self.progress.is_complete() {
270
            status = status
271
                .item(Label::space())
272
                .extend(diffstat(self.stats.into(), self.palette))
273
                .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
274
                .item(Label::new(&file_count(self.stats.files_changed)).fg(FOOTER_VALUE_FG));
275
        }
276
277
        status
278
            .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
279
            .item(Label::new(ALL_HUNKS_MODE_ICON).fg(all_hunks_fg))
280
            .item(Label::space())
281
            .item(Label::new(FULL_FILE_MODE_ICON).fg(full_file_fg))
282
            .style(Style::default().bg(FOOTER_BG))
283
    }
284
}
285
286
/// Context that determines which action hints are shown.
287
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
288
pub(super) enum ActionContext {
289
    /// Commit-list mode.
290
    Commits,
291
    /// Commit diff mode.
292
    Commit {
293
        /// Whether the open commit is rejected.
294
        rejected: bool,
295
        /// Whether the focused hunk can be accepted from this viewport.
296
        can_accept_hunk: bool,
297
    },
298
    /// Hunk comments are being browsed.
299
    HunkBrowse {
300
        /// Whether the owning commit is rejected.
301
        rejected: bool,
302
    },
303
    /// A hunk comment is being edited.
304
    HunkEdit,
305
}
306
307
impl ActionContext {
308
    /// Returns the action hints for this context.
309
    fn actions(self) -> &'static [(&'static str, &'static str)] {
310
        match self {
311
            Self::Commits => COMMITS_ACTIONS,
312
            Self::Commit { .. } => COMMIT_ACTIONS,
313
            Self::HunkBrowse { .. } => HUNK_BROWSE_ACTIONS,
314
            Self::HunkEdit => HUNK_EDIT_ACTIONS,
315
        }
316
    }
317
318
    /// Returns whether the reject key restores the current commit.
319
    fn restores(self) -> bool {
320
        match self {
321
            Self::Commit { rejected, .. } | Self::HunkBrowse { rejected } => rejected,
322
            Self::Commits | Self::HunkEdit => false,
323
        }
324
    }
325
326
    /// Returns whether an action should be shown.
327
    fn shows(self, key: &str) -> bool {
328
        !matches!(
329
            self,
330
            Self::Commit {
331
                can_accept_hunk: false,
332
                ..
333
            }
334
        ) || key != "a"
335
    }
336
}
337
338
/// Bottom chrome containing the status bar and contextual action bar.
339
#[derive(Debug)]
340
pub(super) struct Chrome {
341
    /// Footer status for the active review context.
342
    pub(super) status: Status,
343
    /// Active action context.
344
    pub(super) actions: ActionContext,
345
}
346
347
impl Chrome {
348
    /// Returns the content and bottom chrome areas for a full session frame.
349
    pub(super) fn areas(area: Rect) -> (Rect, Rect) {
350
        area.split_bottom(CHROME_ROWS)
351
    }
352
353
    /// Returns the status and action areas inside the chrome area.
354
    fn rows(area: Rect) -> (Rect, Rect) {
355
        area.split_top(STATUS_ROWS)
356
    }
357
358
    /// Returns the rendered action row.
359
    fn action_line(&self, cols: usize) -> Line {
360
        let mut line = Line::blank();
361
        let mut first = true;
362
        for (key, label) in self.actions.actions() {
363
            if !self.actions.shows(key) {
364
                continue;
365
            }
366
            let label = if *key == "r" && self.actions.restores() {
367
                "restore commit"
368
            } else {
369
                label
370
            };
371
            if !first {
372
                line = line.item(Label::new(ACTION_SEPARATOR).fg(FOOTER_FG));
373
            }
374
            first = false;
375
            line = line
376
                .item(
377
                    Label::new(key)
378
                        .fg(ACTION_KEY_FG)
379
                        .style(Style::default().bold()),
380
                )
381
                .item(Label::space())
382
                .item(Label::new(label).fg(ACTION_LABEL_FG));
383
        }
384
        line.truncated(cols.saturating_sub(2), "").inset(cols)
385
    }
386
}
387
388
impl Widget for Chrome {
389
    fn size(&self, parent: Constraint) -> Size {
390
        Size::new(parent.max.cols, CHROME_ROWS).constrain(parent)
391
    }
392
393
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
394
        if area.is_empty() {
395
            return;
396
        }
397
        let (status_area, action_area) = Self::rows(area);
398
        self.status.render(status_area, buf);
399
        if !action_area.is_empty() {
400
            self.action_line(action_area.cols).render(action_area, buf);
401
        }
402
    }
403
}
404
405
/// Returns the viewer area above the footer chrome.
406
pub(super) fn viewer_area(area: Rect) -> Rect {
407
    Chrome::areas(area).0
408
}
409
410
/// Returns the identity column for one commit-table row.
411
pub(super) fn commit_row(slot: &CommitSlot) -> Line {
412
    let dropped = matches!(slot.state, CommitReviewState::Dropped);
413
    let row_style = if dropped {
414
        Style::default().dim()
415
    } else {
416
        Style::default()
417
    };
418
    let summary_style = if dropped {
419
        Style::default().dim().strikethrough()
420
    } else {
421
        Style::default()
422
    };
423
    Line::new(
424
        Label::new(&slot.commit.id.short())
425
            .fg(colors::rgb::ORANGE)
426
            .style(row_style),
427
    )
428
    .item(Label::space().style(row_style))
429
    .item(Label::new(slot.commit.summary.as_str()).style(summary_style))
430
}
431
432
/// Returns the right-side columns for one commit-table row.
433
///
434
/// Columns are ordered by their wide-layout position: author, age, branches,
435
/// comment count, hunk progress, and diffstat.
436
pub(super) fn commit_row_suffix(
437
    slot: &CommitSlot,
438
    palette: DiffPalette,
439
    now: u64,
440
    largest_change_count: usize,
441
    max_graph_width: usize,
442
) -> [Line; 6] {
443
    let stats = slot.remaining_stats();
444
    let diffstat = match slot.state {
445
        CommitReviewState::Pending => {
446
            history_diffstat(stats, largest_change_count, max_graph_width, palette)
447
        }
448
        CommitReviewState::Accepted | CommitReviewState::Rejected | CommitReviewState::Dropped => {
449
            Line::blank()
450
        }
451
    };
452
453
    let row_style = if matches!(slot.state, CommitReviewState::Dropped) {
454
        Style::default().dim()
455
    } else {
456
        Style::default()
457
    };
458
    let identity_style = if matches!(slot.state, CommitReviewState::Dropped) {
459
        Style::default().dim().strikethrough()
460
    } else {
461
        Style::default()
462
    };
463
    let percent = if slot.progress.total == 0 {
464
        0
465
    } else {
466
        slot.progress
467
            .accepted
468
            .saturating_mul(100)
469
            .div_euclid(slot.progress.total)
470
            .min(100)
471
    };
472
    let hunk_color = match slot.state {
473
        CommitReviewState::Rejected => palette.negative_fg,
474
        CommitReviewState::Accepted => palette.positive_fg,
475
        CommitReviewState::Pending => Color::White,
476
        CommitReviewState::Dropped => colors::fixed::MUTED,
477
    };
478
    let state = match slot.state {
479
        CommitReviewState::Accepted => Label::from_char(REVIEWED_MARK).fg(palette.positive_fg),
480
        CommitReviewState::Rejected => Label::from_char(REJECTED_MARK).fg(palette.negative_fg),
481
        CommitReviewState::Dropped => Label::from_char(DROPPED_MARK).fg(colors::fixed::MUTED),
482
        CommitReviewState::Pending if slot.progress.accepted > 0 => {
483
            Label::from_char(IN_PROGRESS_MARK).fg(Color::White)
484
        }
485
        CommitReviewState::Pending => Label::from_char(PENDING_MARK).fg(colors::fixed::MUTED),
486
    };
487
    let progress = Line::new(state)
488
        .item(Label::space())
489
        .item(Label::new(&format!("{percent}%")).fg(hunk_color))
490
        .style(row_style);
491
    let progress = if matches!(slot.state, CommitReviewState::Accepted) {
492
        progress
493
    } else {
494
        progress
495
            .item(Label::new("/").fg(colors::fixed::MUTED))
496
            .item(
497
                Label::new(&format!("{:<HISTORY_HUNK_COUNT_WIDTH$}", slot.total_hunks))
498
                    .fg(colors::fixed::MUTED),
499
            )
500
    };
501
    let comments = slot
502
        .loaded
503
        .as_ref()
504
        .map_or(slot.comment_count, |loaded| loaded.comments.len());
505
    [
506
        Line::new(Label::new(slot.commit.author.as_str()).fg(HISTORY_VALUE_FG))
507
            .style(identity_style),
508
        Line::new(
509
            Label::from(relative_time(
510
                slot.commit.recency.seconds.into(),
511
                now.into(),
512
            ))
513
            .fg(colors::fixed::MUTED),
514
        )
515
        .style(identity_style),
516
        Line::new(Label::new(&slot.commit.branches.join(", ")).fg(colors::rgb::TEAL))
517
            .style(row_style),
518
        Line::new(Label::new(&format!("{COMMENT_MARK} {comments:>2}")).fg(colors::fixed::MUTED))
519
            .style(row_style),
520
        progress,
521
        diffstat.style(row_style),
522
    ]
523
}
524
525
/// Returns a change count and proportional addition and deletion graph.
526
fn history_diffstat(
527
    stats: DiffStat,
528
    largest_change_count: usize,
529
    max_graph_width: usize,
530
    palette: DiffPalette,
531
) -> Line {
532
    let change_count = stats.insertions + stats.deletions;
533
    let change_kinds = usize::from(stats.insertions > 0) + usize::from(stats.deletions > 0);
534
    let graph_width = if largest_change_count == 0 {
535
        0
536
    } else {
537
        change_count
538
            .saturating_mul(max_graph_width)
539
            .div_ceil(largest_change_count)
540
            .clamp(change_kinds, max_graph_width)
541
    };
542
    let mut addition_width = if change_count == 0 {
543
        0
544
    } else {
545
        stats
546
            .insertions
547
            .saturating_mul(graph_width)
548
            .div_ceil(change_count)
549
            .min(graph_width)
550
    };
551
    if stats.deletions > 0 {
552
        addition_width = addition_width.min(graph_width - 1);
553
    }
554
    let deletion_width = graph_width - addition_width;
555
    let count_width = largest_change_count.max(1).ilog10() as usize + 1;
556
557
    Line::new(Label::new(&format!("{change_count:>count_width$}")).fg(HISTORY_VALUE_FG))
558
        .item(Label::space())
559
        .item(Label::new(&"+".repeat(addition_width)).fg(palette.positive_fg))
560
        .item(Label::new(&"-".repeat(deletion_width)).fg(palette.negative_fg))
561
}
562
563
/// Renders one stored comment as a bordered card.
564
pub(super) fn comment_card_lines(comment: &Comment, selected: bool, cols: usize) -> Vec<Line> {
565
    let border = if selected {
566
        SELECTED_COMMENT_BORDER
567
    } else {
568
        colors::FAINT
569
    };
570
    let bodies = comment
571
        .body
572
        .lines()
573
        .map(|line| Line::new(Label::new(line).fg(Color::White)))
574
        .collect::<Vec<_>>();
575
    let width = bodies.iter().map(Line::width).max().unwrap_or_default();
576
    let header = comment_header(
577
        &comment.author,
578
        &comment_age(comment),
579
        comment_table_content_width(cols).max(width),
580
    );
581
    let mut table = Table::<1, Line>::new(TableOptions {
582
        border: Some(Border::new(border)),
583
        ..TableOptions::bordered()
584
    });
585
    table.header([header]);
586
    for body in bodies {
587
        table.push([body]);
588
    }
589
    table.lines(Constraint::tight(cols))
590
}
591
592
/// Renders an editable comment card with a blank body of `rows` lines.
593
pub(super) fn comment_editor_lines(author: &str, age: &str, rows: usize, cols: usize) -> Vec<Line> {
594
    let body = Line::blank().padded(comment_table_content_width(cols));
595
    let mut table = Table::<1, Line>::new(TableOptions {
596
        border: Some(Border::new(SELECTED_COMMENT_BORDER)),
597
        ..TableOptions::bordered()
598
    });
599
    table.header([comment_header(
600
        author,
601
        age,
602
        comment_table_content_width(cols),
603
    )]);
604
    for _ in 0..rows.max(1) {
605
        table.push([body.clone()]);
606
    }
607
    table.lines(Constraint::tight(cols))
608
}
609
610
/// Returns a comment's age as a human relative timestamp.
611
pub(super) fn comment_age(comment: &Comment) -> String {
612
    relative_time(comment.timestamp.into(), current_timestamp().into())
613
}
614
615
/// Returns the comment-card content width: the rendered width minus the
616
/// border and padding columns on both sides.
617
fn comment_table_content_width(cols: usize) -> usize {
618
    cols.saturating_sub(2 * COMMENT_CARD_CHROME_COLS)
619
}
620
621
/// Returns a comment-table header from displayable fields.
622
fn comment_header(author: &str, timestamp: &str, body_width: usize) -> Line {
623
    Line::spaced([
624
        Label::new(author).style(Style::default().fg(Color::White).bold()),
625
        Label::new(timestamp).fg(colors::fixed::DIM),
626
    ])
627
    .padded(body_width)
628
}
629
630
/// Returns a human relative timestamp in the largest whole unit.
631
fn relative_time(timestamp: i128, now: i128) -> String {
632
    /// Time units from largest to smallest, as seconds and unit name.
633
    const UNITS: [(u128, &str); 5] = [
634
        (31_536_000, "year"),
635
        (2_592_000, "month"),
636
        (86_400, "day"),
637
        (3_600, "hour"),
638
        (60, "minute"),
639
    ];
640
    let direction = timestamp.cmp(&now);
641
    let elapsed = timestamp.abs_diff(now);
642
643
    for (seconds, unit) in UNITS {
644
        match (direction, elapsed / seconds) {
645
            (_, 0) => continue,
646
            (Ordering::Greater, 1) => return format!("in 1 {unit}"),
647
            (Ordering::Greater, count) => return format!("in {count} {unit}s"),
648
            (_, 1) => return format!("1 {unit} ago"),
649
            (_, count) => return format!("{count} {unit}s ago"),
650
        }
651
    }
652
    if direction == Ordering::Greater {
653
        "in less than a minute".to_owned()
654
    } else {
655
        "just now".to_owned()
656
    }
657
}
658
659
/// Returns the current Unix timestamp.
660
pub(super) fn current_timestamp() -> u64 {
661
    SystemTime::now()
662
        .duration_since(UNIX_EPOCH)
663
        .unwrap_or_default()
664
        .as_secs()
665
}
666
667
#[cfg(test)]
668
mod tests {
669
    use super::*;
670
671
    use crate::backend::Commit;
672
    use rustik_repo::CommitTime;
673
674
    #[test]
675
    fn viewer_area_reserves_footer() {
676
        assert_eq!(
677
            viewer_area(Rect::new(0, 0, 80, 20)),
678
            Rect::new(0, 0, 80, 18)
679
        );
680
        assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0));
681
    }
682
683
    #[test]
684
    fn chrome_areas_reserve_footer() {
685
        assert_eq!(
686
            Chrome::areas(Rect::new(0, 0, 80, 20)),
687
            (Rect::new(0, 0, 80, 18), Rect::new(0, 18, 80, 2))
688
        );
689
        assert_eq!(
690
            Chrome::areas(Rect::new(0, 0, 80, 1)),
691
            (Rect::new(0, 0, 80, 0), Rect::new(0, 0, 80, 1))
692
        );
693
    }
694
695
    #[test]
696
    fn action_context_changes_action_hints() {
697
        assert!(
698
            ActionContext::Commit {
699
                rejected: false,
700
                can_accept_hunk: true,
701
            }
702
            .actions()
703
            .iter()
704
            .any(|(_, label)| *label == "accept hunk")
705
        );
706
        assert!(
707
            ActionContext::Commits
708
                .actions()
709
                .iter()
710
                .any(|(_, label)| *label == "reject commit")
711
        );
712
        assert!(
713
            ActionContext::HunkBrowse { rejected: false }
714
                .actions()
715
                .iter()
716
                .any(|(_, label)| *label == "reject commit")
717
        );
718
        assert!(
719
            ActionContext::HunkEdit
720
                .actions()
721
                .iter()
722
                .any(|(_, label)| *label == "save")
723
        );
724
    }
725
726
    #[test]
727
    fn chrome_error_replaces_status() {
728
        let mut chrome = Chrome {
729
            status: Status {
730
                mode: "commit",
731
                context: StatusContext::Commit {
732
                    short: "1234567".to_owned(),
733
                    summary: "summary".to_owned(),
734
                    state: CommitReviewState::Pending,
735
                },
736
                progress: ReviewProgress::default(),
737
                stats: DiffStat::default(),
738
                palette: DiffPalette::default(),
739
                visibility: Visibility::default(),
740
                error: Some("patch does not apply".to_owned()),
741
                loading: None,
742
            },
743
            actions: ActionContext::Commit {
744
                rejected: false,
745
                can_accept_hunk: true,
746
            },
747
        };
748
        assert!(chrome.action_line(80).to_string().contains("q quit"));
749
        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 2));
750
751
        chrome.render(buffer.area(), &mut buffer);
752
753
        let status = buffer.line(0);
754
        assert!(status.contains("patch does not apply"));
755
        assert!(!status.contains("brain"));
756
        assert!(buffer.line(1).contains("q quit"));
757
    }
758
759
    #[test]
760
    fn loading_status_preserves_application_and_mode() {
761
        let mut status = Status {
762
            mode: "commit",
763
            context: StatusContext::Commit {
764
                short: "1234567".to_owned(),
765
                summary: "summary".to_owned(),
766
                state: CommitReviewState::Pending,
767
            },
768
            progress: ReviewProgress::default(),
769
            stats: DiffStat::default(),
770
            palette: DiffPalette::default(),
771
            visibility: Visibility::default(),
772
            error: None,
773
            loading: Some(("accepting hunk", 1)),
774
        };
775
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 1));
776
777
        status.render(buffer.area(), &mut buffer);
778
        let rendered = buffer.line(0);
779
780
        assert!(rendered.contains(" brain "));
781
        assert!(rendered.contains(" commit "));
782
        assert!(rendered.contains("⠙ accepting hunk"));
783
        assert!(!rendered.contains("1234567"));
784
        assert!(!rendered.contains("summary"));
785
    }
786
787
    #[test]
788
    fn completed_commit_status_hides_diff_summary() {
789
        let mut status = Status {
790
            mode: "commit",
791
            context: StatusContext::Commit {
792
                short: "1234567".to_owned(),
793
                summary: "summary".to_owned(),
794
                state: CommitReviewState::Accepted,
795
            },
796
            progress: ReviewProgress {
797
                accepted: 5,
798
                total: 5,
799
            },
800
            stats: DiffStat::default(),
801
            palette: DiffPalette::default(),
802
            visibility: Visibility::default(),
803
            error: None,
804
            loading: None,
805
        };
806
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 1));
807
808
        status.render(buffer.area(), &mut buffer);
809
        let rendered = (0..buffer.area().cols)
810
            .map(|x| buffer.get(x, 0).unwrap().glyph())
811
            .collect::<String>();
812
813
        assert!(rendered.ends_with("━━━━━━━━ · ✔ ↕ "));
814
    }
815
816
    #[test]
817
    fn completed_commit_rows_render_final_state() {
818
        let now = 2_000_000_000;
819
        let stats = DiffStat {
820
            files_changed: 1,
821
            insertions: 2,
822
            deletions: 3,
823
        };
824
        let mut slot = CommitSlot {
825
            commit: Commit {
826
                id: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
827
                summary: "Summary".to_owned(),
828
                author: "Alice".to_owned(),
829
                branches: vec!["main".to_owned()],
830
                recency: CommitTime {
831
                    seconds: now - 3_600,
832
                },
833
                stats,
834
            },
835
            progress: ReviewProgress {
836
                accepted: 0,
837
                total: 1,
838
            },
839
            total_hunks: 1,
840
            comment_count: 3,
841
            state: CommitReviewState::Pending,
842
            remaining_stats: stats,
843
            document: None,
844
            identities: None,
845
            loaded: None,
846
        };
847
848
        for (state, marker) in [
849
            (CommitReviewState::Accepted, REVIEWED_MARK),
850
            (CommitReviewState::Rejected, REJECTED_MARK),
851
        ] {
852
            slot.state = state;
853
            let progress = commit_row_suffix(
854
                &slot,
855
                DiffPalette::default(),
856
                now as u64,
857
                stats.insertions + stats.deletions,
858
                8,
859
            )[4]
860
            .to_string();
861
            assert!(progress.starts_with(marker));
862
            assert!(
863
                commit_row_suffix(
864
                    &slot,
865
                    DiffPalette::default(),
866
                    now as u64,
867
                    stats.insertions + stats.deletions,
868
                    8,
869
                )[5]
870
                .to_string()
871
                .is_empty()
872
            );
873
        }
874
875
        slot.state = CommitReviewState::Dropped;
876
        let [mut author, mut age, _, comments, progress, diffstat] = commit_row_suffix(
877
            &slot,
878
            DiffPalette::default(),
879
            now as u64,
880
            stats.insertions + stats.deletions,
881
            8,
882
        );
883
        assert!(diffstat.to_string().is_empty());
884
        assert_eq!(progress.to_string(), format!("{DROPPED_MARK} 0%/1   "));
885
        assert_eq!(comments.to_string(), "🗩  3");
886
887
        let mut author_buffer = Buffer::empty(Rect::new(0, 0, slot.commit.author.len(), 1));
888
        let mut age_buffer = Buffer::empty(Rect::new(0, 0, 16, 1));
889
        author.render(author_buffer.area(), &mut author_buffer);
890
        age.render(age_buffer.area(), &mut age_buffer);
891
892
        assert_eq!(
893
            author_buffer.get(0, 0).unwrap().style(),
894
            Style::default().fg(HISTORY_VALUE_FG).dim().strikethrough()
895
        );
896
        assert_eq!(
897
            age_buffer.get(0, 0).unwrap().style(),
898
            Style::default()
899
                .fg(colors::fixed::MUTED)
900
                .dim()
901
                .strikethrough()
902
        );
903
904
        slot.state = CommitReviewState::Pending;
905
        assert!(
906
            commit_row_suffix(
907
                &slot,
908
                DiffPalette::default(),
909
                now as u64,
910
                stats.insertions + stats.deletions,
911
                8,
912
            )[4]
913
            .to_string()
914
            .starts_with(PENDING_MARK)
915
        );
916
        slot.progress.accepted = 1;
917
        assert!(
918
            commit_row_suffix(
919
                &slot,
920
                DiffPalette::default(),
921
                now as u64,
922
                stats.insertions + stats.deletions,
923
                8,
924
            )[4]
925
            .to_string()
926
            .starts_with(IN_PROGRESS_MARK)
927
        );
928
929
        for (state, accepted_lines, total_lines, expected_percent, expected_color) in [
930
            (CommitReviewState::Pending, 0, 4, 0, Color::White),
931
            (CommitReviewState::Pending, 1, 4, 25, Color::White),
932
            (CommitReviewState::Pending, 399, 400, 99, Color::White),
933
            (
934
                CommitReviewState::Accepted,
935
                4,
936
                4,
937
                100,
938
                DiffPalette::default().positive_fg,
939
            ),
940
            (
941
                CommitReviewState::Rejected,
942
                0,
943
                4,
944
                0,
945
                DiffPalette::default().negative_fg,
946
            ),
947
        ] {
948
            slot.state = state;
949
            slot.progress = ReviewProgress {
950
                accepted: accepted_lines,
951
                total: total_lines,
952
            };
953
            slot.total_hunks = 2;
954
            let [_, _, _, _, mut progress, _] = commit_row_suffix(
955
                &slot,
956
                DiffPalette::default(),
957
                now as u64,
958
                stats.insertions + stats.deletions,
959
                8,
960
            );
961
            let rendered = progress.to_string();
962
            if matches!(state, CommitReviewState::Accepted) {
963
                assert_eq!(rendered, format!("{REVIEWED_MARK} {expected_percent}%"));
964
            } else {
965
                assert!(rendered.contains(&format!("{expected_percent}%/2")));
966
            }
967
            let mut buffer = Buffer::empty(Rect::new(0, 0, 16, 1));
968
            progress.render(buffer.area(), &mut buffer);
969
            let slash_col = 2 + expected_percent.to_string().len() + 1;
970
971
            let icon_color = match (state, accepted_lines) {
972
                (CommitReviewState::Rejected, _) => DiffPalette::default().negative_fg,
973
                (CommitReviewState::Accepted, _) => DiffPalette::default().positive_fg,
974
                (CommitReviewState::Pending, 0) => colors::fixed::MUTED,
975
                (CommitReviewState::Pending, _) => Color::White,
976
                _ => unreachable!(),
977
            };
978
979
            assert_eq!(
980
                buffer.get(0, 0).unwrap().style(),
981
                Style::default().fg(icon_color)
982
            );
983
            assert_eq!(
984
                buffer.get(2, 0).unwrap().style(),
985
                Style::default().fg(expected_color)
986
            );
987
            if !matches!(state, CommitReviewState::Accepted) {
988
                assert_eq!(
989
                    buffer.get(slash_col, 0).unwrap().style(),
990
                    Style::default().fg(colors::fixed::MUTED)
991
                );
992
                assert_eq!(
993
                    buffer.get(slash_col + 1, 0).unwrap().style(),
994
                    Style::default().fg(colors::fixed::MUTED)
995
                );
996
            }
997
        }
998
    }
999
1000
    #[test]
1001
    fn history_diffstat_scales_against_largest_commit() {
1002
        let palette = DiffPalette::default();
1003
        let largest = DiffStat {
1004
            files_changed: 1,
1005
            insertions: 6,
1006
            deletions: 4,
1007
        };
1008
        let smaller = DiffStat {
1009
            files_changed: 1,
1010
            insertions: 2,
1011
            deletions: 3,
1012
        };
1013
        let deletion = DiffStat {
1014
            files_changed: 1,
1015
            insertions: 999,
1016
            deletions: 1,
1017
        };
1018
        let small_mixed = DiffStat {
1019
            files_changed: 1,
1020
            insertions: 1,
1021
            deletions: 1,
1022
        };
1023
1024
        assert_eq!(
1025
            history_diffstat(largest, 10, 8, palette).to_string(),
1026
            "10 +++++---"
1027
        );
1028
        assert_eq!(
1029
            history_diffstat(smaller, 10, 8, palette).to_string(),
1030
            " 5 ++--"
1031
        );
1032
        assert_eq!(
1033
            history_diffstat(deletion, 1_000, 8, palette).to_string(),
1034
            "1000 +++++++-"
1035
        );
1036
        assert_eq!(
1037
            history_diffstat(small_mixed, 1_000, 8, palette).to_string(),
1038
            "   2 +-"
1039
        );
1040
        let wide = history_diffstat(largest, 10, 32, palette).to_string();
1041
        let uncapped = history_diffstat(largest, 10, 64, palette).to_string();
1042
        assert_eq!(wide.chars().count(), 35);
1043
        assert!(uncapped.chars().count() > wide.chars().count());
1044
    }
1045
1046
    #[test]
1047
    fn comment_card_lines_render_a_bordered_comment_card() {
1048
        let comment = Comment {
1049
            id: 1.into(),
1050
            author: "alice".to_owned(),
1051
            timestamp: current_timestamp(),
1052
            body: "first\nsecond".to_owned(),
1053
        };
1054
1055
        let lines = comment_card_lines(&comment, true, 40);
1056
        let text = lines
1057
            .iter()
1058
            .map(ToString::to_string)
1059
            .collect::<Vec<_>>()
1060
            .join("\n");
1061
1062
        assert_eq!(lines.len(), COMMENT_CARD_CHROME_ROWS + 2);
1063
        assert!(text.contains("alice"), "text: {text:?}");
1064
        assert!(text.contains("just now"), "text: {text:?}");
1065
        assert!(lines.iter().any(|line| line.to_string().contains("first")));
1066
        assert!(lines.iter().any(|line| line.to_string().contains("second")));
1067
        assert!(!text.contains('🗨'), "text: {text:?}");
1068
    }
1069
1070
    #[test]
1071
    fn relative_time_uses_largest_whole_unit() {
1072
        let now = 2_000_000_000;
1073
1074
        assert_eq!(relative_time(now, now), "just now");
1075
        assert_eq!(relative_time(now - 60, now), "1 minute ago");
1076
        assert_eq!(relative_time(now - 3_600, now), "1 hour ago");
1077
        assert_eq!(relative_time(now - 86_400, now), "1 day ago");
1078
        assert_eq!(relative_time(now - 2_592_000, now), "1 month ago");
1079
        assert_eq!(relative_time(now - 31_536_000, now), "1 year ago");
1080
    }
1081
1082
    #[test]
1083
    fn relative_time_preserves_future_direction() {
1084
        let now = 2_000_000_000;
1085
1086
        assert_eq!(relative_time(now + 1, now), "in less than a minute");
1087
        assert_eq!(relative_time(now + 60, now), "in 1 minute");
1088
        assert_eq!(relative_time(now + 7_200, now), "in 2 hours");
1089
    }
1090
}