//! Status and chrome rendering for the review session. use std::cmp::Ordering; use std::time::{SystemTime, UNIX_EPOCH}; use rustik_diff::{ DiffPalette, ReviewProgress, diffstat, file_count, progress_bar, recoverable_error, }; use rustik_repo::DiffStat; use rustik_tui::{ Border, Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Table, TableOptions, Widget, colors, }; use crate::backend::CommitReviewState; use crate::comments::{COMMENT_MARK, Comment}; use crate::review::{FileVisibility, HunkVisibility, Visibility}; use super::commit::CommitSlot; /// Number of rows used by the status bar. const STATUS_ROWS: usize = 1; /// Number of rows used by the action bar. const ACTION_ROWS: usize = 1; /// Number of rows reserved for the bottom footer when possible. const CHROME_ROWS: usize = STATUS_ROWS + ACTION_ROWS; /// Empty columns between status content and the status bar's right edge. const STATUS_RIGHT_PADDING: usize = 1; /// Maximum width of a history diffstat graph. pub(super) const HISTORY_DIFFSTAT_MAX_WIDTH: usize = 32; /// Columns reserved for the total hunk count in commit history. const HISTORY_HUNK_COUNT_WIDTH: usize = 4; /// Foreground color for dim footer text. const FOOTER_FG: Color = Color::Fixed(240); /// Foreground color for prominent history values. const HISTORY_VALUE_FG: Color = Color::Fixed(246); /// Background color for the footer row, matching file border chrome. const FOOTER_BG: Color = colors::FAINT; /// Background color for the brain application badge. pub(crate) const BRAIN_BADGE_BG: Color = Color::RGB(124, 36, 32); /// Background color for the active-mode badge. const MODE_BADGE_BG: Color = Color::RGB(68, 68, 68); /// Foreground color for the current commit hash. const FOOTER_HASH_FG: Color = Color::Fixed(250); /// Foreground color for neutral footer values. const FOOTER_VALUE_FG: Color = FOOTER_HASH_FG; /// Foreground color for the current commit summary. const FOOTER_SUMMARY_FG: Color = Color::Fixed(153); /// Border color for the selected comment in the hunk view. const SELECTED_COMMENT_BORDER: Color = Color::Fixed(239); /// Background color for the selected commit, matching the active file row. pub(super) const SELECTED_COMMIT_BG: Color = Color::Fixed(235); /// Marker shown beside a commit whose hunks have all been accepted: ✔. const REVIEWED_MARK: char = '✔'; /// Marker shown beside a rejected commit: ✗. const REJECTED_MARK: char = '✗'; /// Marker shown beside a dropped commit. const DROPPED_MARK: char = '-'; /// Marker shown beside a commit that has not been reviewed. const PENDING_MARK: char = '○'; /// Marker shown beside a commit whose review is in progress. const IN_PROGRESS_MARK: char = '◐'; /// Marker highlighted when all hunks are visible in the footer: ✔. const ALL_HUNKS_MODE_ICON: &str = "✔"; /// Marker shown when full-file mode is visible in the footer: ↕. const FULL_FILE_MODE_ICON: &str = "↕"; /// Separator shown between footer status segments: ·. const FOOTER_SEPARATOR: &str = " · "; /// Marker used when footer text truncates: …. const FOOTER_ELLIPSIS: &str = "…"; /// Frames used by the repository-operation status spinner. const SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\']; /// Separator shown between plain action hints. const ACTION_SEPARATOR: &str = " · "; /// Key label shown for Tab: ⭾. const TAB_KEY: &str = "⭾"; /// Key label shown for Return: ⮐. const RETURN_KEY: &str = "⮐"; /// Key label shown for Ctrl-Return. const CTRL_RETURN_KEY: &str = "ctrl-⮐"; /// Foreground color for contextual action labels. const ACTION_LABEL_FG: Color = Color::Fixed(244); /// Foreground color for contextual action keys. const ACTION_KEY_FG: Color = Color::Fixed(250); /// Foreground color for active context-expansion mode. const FULL_FILE_MODE_FG: Color = colors::rgb::TEAL; /// Action hints shown in commit-list mode. const COMMITS_ACTIONS: &[(&str, &str)] = &[ (TAB_KEY, "commit"), ("j/k", "select"), (RETURN_KEY, "open"), ("r", "reject commit"), ("d", "drop commit"), ("q", "quit"), ]; /// Action hints shown in commit diff mode. const COMMIT_ACTIONS: &[(&str, &str)] = &[ (TAB_KEY, "history"), ("j/k", "hunk"), ("n/p", "file"), ("a", "accept hunk"), ("r", "reject commit"), ("d", "drop commit"), ("u", "undo"), ("c", "comment"), ]; /// Action hints shown while browsing hunk comments. const HUNK_BROWSE_ACTIONS: &[(&str, &str)] = &[ (TAB_KEY, "history"), ("r", "reject commit"), ("c", "new"), ("e", "edit"), ("d", "delete"), ("n/p", "select"), ("esc", "commit"), ]; /// Action hints shown while editing a hunk comment. const HUNK_EDIT_ACTIONS: &[(&str, &str)] = &[ (RETURN_KEY, "newline"), (CTRL_RETURN_KEY, "save"), ("esc", "cancel"), (TAB_KEY, "history"), ]; /// Rendered rows in one stored comment card. pub(super) const COMMENT_CARD_ROWS: usize = 4; /// Rows of card chrome around a comment body: the top border, the header row, /// and the bottom border. pub(super) const COMMENT_CARD_CHROME_ROWS: usize = 3; /// Columns of card chrome on each side of a comment body: the border and its /// padding. pub(super) const COMMENT_CARD_CHROME_COLS: usize = 2; /// Context shown on the left side of the footer status. #[derive(Debug)] pub(super) enum StatusContext { /// Selected commit identity and summary. Commit { /// Abbreviated commit hash. short: String, /// First line of the commit message. summary: String, }, /// Reviewed revision range. Range(String), } /// Footer status describing the current review context and progress. #[derive(Debug)] pub(super) struct Status { /// Active review mode name. pub(super) mode: &'static str, /// Review context displayed for the active mode. pub(super) context: StatusContext, /// Accepted-line progress for the active review context. pub(super) progress: ReviewProgress, /// Aggregated diff size for the active review context. pub(super) stats: DiffStat, /// Diff palette used for stat and review colors. pub(super) palette: DiffPalette, /// Visibility modes for the active review view. pub(super) visibility: Visibility, /// Most recent recoverable session error. pub(super) error: Option, /// Active repository operation and animation frame. pub(super) loading: Option<(&'static str, usize)>, } impl Widget for Status { fn size(&self, parent: Constraint) -> Size { Size::new(parent.max.cols, STATUS_ROWS).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { if area.is_empty() { return; } Self::background(area.cols).render(area, buf); self.bar(area.cols).render(area, buf); } } impl Status { /// Returns the full-width status row background. fn background(cols: usize) -> Line { Line::new(Label::space().bg(FOOTER_BG)).padded(cols) } /// Returns the bottom status row content. fn bar(&self, cols: usize) -> HStack<'_> { if let Some(error) = &self.error { return HStack::default() .child(recoverable_error(error, FOOTER_VALUE_FG, FOOTER_BG).truncated(cols, "")); } if let Some((operation, frame)) = self.loading { let spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.len()]; return HStack::default().child( Line::blank() .item(Label::from_char(spinner).fg(FOOTER_VALUE_FG)) .item(Label::space()) .item(Label::new(operation).fg(FOOTER_VALUE_FG)) .style(Style::default().bg(FOOTER_BG)) .truncated(cols, FOOTER_ELLIPSIS), ); } let right = self.right_status(); let left_width = cols .saturating_sub(right.width()) .saturating_sub(STATUS_RIGHT_PADDING) .saturating_sub(1); HStack::default() .child(self.left_status().truncated(left_width, FOOTER_ELLIPSIS)) .spacer() .child(right) .child(Line::new(Label::space().bg(FOOTER_BG)).padded(STATUS_RIGHT_PADDING)) } /// Returns the left status section with application, mode, and review context. fn left_status(&self) -> Line { let context = match &self.context { StatusContext::Commit { short, summary } => Line::blank() .item(Label::new(short).fg(FOOTER_HASH_FG)) .item(Label::space()) .item(Label::new(summary).fg(FOOTER_SUMMARY_FG)), StatusContext::Range(range) => Line::new(Label::new(range).fg(FOOTER_SUMMARY_FG)), }; Line::blank() .item( Label::new(" brain ") .fg(Color::White) .bg(BRAIN_BADGE_BG) .style(Style::default().bold()), ) .item( Label::new(&format!(" {} ", self.mode)) .fg(Color::White) .bg(MODE_BADGE_BG) .style(Style::default().bold()), ) .item(Label::space()) .extend(context) .style(Style::default().bg(FOOTER_BG)) } /// Returns the right status section with review state and diff statistics. fn right_status(&self) -> Line { let all_hunks_fg = match self.visibility.hunks { HunkVisibility::Pending => FOOTER_FG, HunkVisibility::All => self.palette.positive_fg, }; let full_file_fg = match self.visibility.file { FileVisibility::Context => FOOTER_FG, FileVisibility::Full => FULL_FILE_MODE_FG, }; let mut status = Line::blank().extend(progress_bar(self.progress, self.palette, FOOTER_FG)); if !matches!(self.context, StatusContext::Commit { .. }) || !self.progress.is_complete() { status = status .item(Label::space()) .extend(diffstat(self.stats.into(), self.palette)) .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG)) .item(Label::new(&file_count(self.stats.files_changed)).fg(FOOTER_VALUE_FG)); } status .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG)) .item(Label::new(ALL_HUNKS_MODE_ICON).fg(all_hunks_fg)) .item(Label::space()) .item(Label::new(FULL_FILE_MODE_ICON).fg(full_file_fg)) .style(Style::default().bg(FOOTER_BG)) } } /// Context that determines which action hints are shown. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum ActionContext { /// Commit-list mode. Commits, /// Commit diff mode. Commit, /// Hunk comments are being browsed. HunkBrowse, /// A hunk comment is being edited. HunkEdit, } impl ActionContext { /// Returns the action hints for this context. fn actions(self) -> &'static [(&'static str, &'static str)] { match self { Self::Commits => COMMITS_ACTIONS, Self::Commit => COMMIT_ACTIONS, Self::HunkBrowse => HUNK_BROWSE_ACTIONS, Self::HunkEdit => HUNK_EDIT_ACTIONS, } } } /// Bottom chrome containing the status bar and contextual action bar. #[derive(Debug)] pub(super) struct Chrome { /// Footer status for the active review context. pub(super) status: Status, /// Active action context. pub(super) actions: ActionContext, } impl Chrome { /// Returns the content and bottom chrome areas for a full session frame. pub(super) fn areas(area: Rect) -> (Rect, Rect) { area.split_bottom(CHROME_ROWS) } /// Returns the status and action areas inside the chrome area. fn rows(area: Rect) -> (Rect, Rect) { area.split_top(STATUS_ROWS) } /// Returns the rendered action row. fn action_line(&self, cols: usize) -> Line { let mut line = Line::blank(); let mut first = true; for (key, label) in self.actions.actions() { if !first { line = line.item(Label::new(ACTION_SEPARATOR).fg(FOOTER_FG)); } first = false; line = line .item( Label::new(key) .fg(ACTION_KEY_FG) .style(Style::default().bold()), ) .item(Label::space()) .item(Label::new(label).fg(ACTION_LABEL_FG)); } line.truncated(cols.saturating_sub(2), "").inset(cols) } } impl Widget for Chrome { fn size(&self, parent: Constraint) -> Size { Size::new(parent.max.cols, CHROME_ROWS).constrain(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { if area.is_empty() { return; } let (status_area, action_area) = Self::rows(area); self.status.render(status_area, buf); if !action_area.is_empty() { let mut line = if self.status.error.is_some() { Status::background(action_area.cols) } else { self.action_line(action_area.cols) }; line.render(action_area, buf); } } } /// Returns the viewer area above the footer chrome. pub(super) fn viewer_area(area: Rect) -> Rect { Chrome::areas(area).0 } /// Returns the state and leading columns for one commit-table row. pub(super) fn commit_row(slot: &CommitSlot, palette: DiffPalette) -> [Line; 3] { let dropped = matches!(slot.state, CommitReviewState::Dropped); let row_style = if dropped { Style::default().dim() } else { Style::default() }; let state = match slot.state { CommitReviewState::Accepted => Label::from_char(REVIEWED_MARK).fg(palette.positive_fg), CommitReviewState::Rejected => Label::from_char(REJECTED_MARK).fg(palette.negative_fg), CommitReviewState::Dropped => Label::from_char(DROPPED_MARK).fg(colors::fixed::MUTED), CommitReviewState::Pending if slot.accepted_hunks > 0 => { Label::from_char(IN_PROGRESS_MARK).fg(colors::rgb::ORANGE) } CommitReviewState::Pending => Label::from_char(PENDING_MARK).fg(colors::fixed::MUTED), }; [ Line::new(state).style(row_style), Line::new(Label::new(&slot.commit.id.short()).fg(colors::rgb::ORANGE)).style(row_style), Line::new(slot.commit.summary.as_str()).style(if dropped { Style::default().dim().strikethrough() } else { Style::default() }), ] } /// Returns the right-side columns for one commit-table row. /// /// Columns are ordered by their wide-layout position: hunk progress, author, /// age, branches, comment count, and diffstat. pub(super) fn commit_row_suffix( slot: &CommitSlot, palette: DiffPalette, now: u64, largest_change_count: usize, max_graph_width: usize, ) -> [Line; 6] { let stats = slot.remaining_stats(); let diffstat = match slot.state { CommitReviewState::Pending => { history_diffstat(stats, largest_change_count, max_graph_width, palette) } CommitReviewState::Accepted | CommitReviewState::Rejected | CommitReviewState::Dropped => { Line::blank() } }; let row_style = if matches!(slot.state, CommitReviewState::Dropped) { Style::default().dim() } else { Style::default() }; let identity_style = if matches!(slot.state, CommitReviewState::Dropped) { Style::default().dim().strikethrough() } else { Style::default() }; let percent = slot .accepted_hunks .saturating_mul(100) .checked_div(slot.total_hunks) .unwrap_or(0); let hunk_color = match (slot.state, percent) { (CommitReviewState::Rejected, _) => palette.negative_fg, (_, 0) => colors::fixed::MUTED, (_, 100) => palette.positive_fg, _ => colors::rgb::ORANGE, }; let hunks = Line::new( Label::new(&format!( "{percent}%/{:2}")).fg(colors::fixed::MUTED)) .style(row_style), diffstat.style(row_style), ] } /// Returns a change count and proportional addition and deletion graph. fn history_diffstat( stats: DiffStat, largest_change_count: usize, max_graph_width: usize, palette: DiffPalette, ) -> Line { let change_count = stats.insertions + stats.deletions; let change_kinds = usize::from(stats.insertions > 0) + usize::from(stats.deletions > 0); let graph_width = if largest_change_count == 0 { 0 } else { change_count .saturating_mul(max_graph_width) .div_ceil(largest_change_count) .clamp(change_kinds, max_graph_width) }; let mut addition_width = if change_count == 0 { 0 } else { stats .insertions .saturating_mul(graph_width) .div_ceil(change_count) .min(graph_width) }; if stats.deletions > 0 { addition_width = addition_width.min(graph_width - 1); } let deletion_width = graph_width - addition_width; let count_width = largest_change_count.max(1).ilog10() as usize + 1; Line::new(Label::new(&format!("{change_count:>count_width$}")).fg(HISTORY_VALUE_FG)) .item(Label::space()) .item(Label::new(&"+".repeat(addition_width)).fg(palette.positive_fg)) .item(Label::new(&"-".repeat(deletion_width)).fg(palette.negative_fg)) } /// Renders one stored comment as a bordered card. pub(super) fn comment_card_lines(comment: &Comment, selected: bool, cols: usize) -> Vec { let border = if selected { SELECTED_COMMENT_BORDER } else { colors::FAINT }; let body = Line::new(Label::new(&comment.body.replace('\n', " ")).fg(Color::White)); let header = comment_header( &comment.author, &comment_age(comment), comment_table_content_width(cols).max(body.width()), ); let mut table = Table::<1, Line>::new(TableOptions { border: Some(Border::new(border)), ..TableOptions::bordered() }); table.header([header]); table.push([body]); table.lines(Constraint::tight(cols)) } /// Renders an editable comment card with a blank body of `rows` lines. pub(super) fn comment_editor_lines(author: &str, age: &str, rows: usize, cols: usize) -> Vec { let body = Line::blank().padded(comment_table_content_width(cols)); let mut table = Table::<1, Line>::new(TableOptions { border: Some(Border::new(SELECTED_COMMENT_BORDER)), ..TableOptions::bordered() }); table.header([comment_header( author, age, comment_table_content_width(cols), )]); for _ in 0..rows.max(1) { table.push([body.clone()]); } table.lines(Constraint::tight(cols)) } /// Returns a comment's age as a human relative timestamp. pub(super) fn comment_age(comment: &Comment) -> String { relative_time(comment.timestamp.into(), current_timestamp().into()) } /// Returns the comment-card content width: the rendered width minus the /// border and padding columns on both sides. fn comment_table_content_width(cols: usize) -> usize { cols.saturating_sub(2 * COMMENT_CARD_CHROME_COLS) } /// Returns a comment-table header from displayable fields. fn comment_header(author: &str, timestamp: &str, body_width: usize) -> Line { Line::spaced([ Label::new(author).style(Style::default().fg(Color::White).bold()), Label::new(timestamp).fg(colors::fixed::DIM), ]) .padded(body_width) } /// Returns a human relative timestamp in the largest whole unit. fn relative_time(timestamp: i128, now: i128) -> String { /// Time units from largest to smallest, as seconds and unit name. const UNITS: [(u128, &str); 5] = [ (31_536_000, "year"), (2_592_000, "month"), (86_400, "day"), (3_600, "hour"), (60, "minute"), ]; let direction = timestamp.cmp(&now); let elapsed = timestamp.abs_diff(now); for (seconds, unit) in UNITS { match (direction, elapsed / seconds) { (_, 0) => continue, (Ordering::Greater, 1) => return format!("in 1 {unit}"), (Ordering::Greater, count) => return format!("in {count} {unit}s"), (_, 1) => return format!("1 {unit} ago"), (_, count) => return format!("{count} {unit}s ago"), } } if direction == Ordering::Greater { "in less than a minute".to_owned() } else { "just now".to_owned() } } /// Returns the current Unix timestamp. pub(super) fn current_timestamp() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs() } #[cfg(test)] mod tests { use super::*; use crate::backend::Commit; use rustik_repo::CommitTime; #[test] fn viewer_area_reserves_footer() { assert_eq!( viewer_area(Rect::new(0, 0, 80, 20)), Rect::new(0, 0, 80, 18) ); assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0)); } #[test] fn chrome_areas_reserve_footer() { assert_eq!( Chrome::areas(Rect::new(0, 0, 80, 20)), (Rect::new(0, 0, 80, 18), Rect::new(0, 18, 80, 2)) ); assert_eq!( Chrome::areas(Rect::new(0, 0, 80, 1)), (Rect::new(0, 0, 80, 0), Rect::new(0, 0, 80, 1)) ); } #[test] fn action_context_changes_action_hints() { assert!( ActionContext::Commit .actions() .iter() .any(|(_, label)| *label == "accept hunk") ); assert!( ActionContext::Commits .actions() .iter() .any(|(_, label)| *label == "reject commit") ); assert!( ActionContext::HunkBrowse .actions() .iter() .any(|(_, label)| *label == "reject commit") ); assert!( ActionContext::HunkEdit .actions() .iter() .any(|(_, label)| *label == "save") ); } #[test] fn chrome_error_replaces_status() { let mut chrome = Chrome { status: Status { mode: "commit", context: StatusContext::Commit { short: "1234567".to_owned(), summary: "summary".to_owned(), }, progress: ReviewProgress::default(), stats: DiffStat::default(), palette: DiffPalette::default(), visibility: Visibility::default(), error: Some("patch does not apply".to_owned()), loading: None, }, actions: ActionContext::Commit, }; let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 2)); chrome.render(buffer.area(), &mut buffer); let status = buffer.line(0); assert!(status.contains("patch does not apply")); assert!(!status.contains("brain")); } #[test] fn completed_commit_status_hides_diff_summary() { let mut status = Status { mode: "commit", context: StatusContext::Commit { short: "1234567".to_owned(), summary: "summary".to_owned(), }, progress: ReviewProgress { accepted: 5, total: 5, }, stats: DiffStat::default(), palette: DiffPalette::default(), visibility: Visibility::default(), error: None, loading: None, }; let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 1)); status.render(buffer.area(), &mut buffer); let rendered = (0..buffer.area().cols) .map(|x| buffer.get(x, 0).unwrap().glyph()) .collect::(); assert!(rendered.ends_with("━━━━━━━━ · ✔ ↕ ")); } #[test] fn completed_commit_rows_render_final_state() { let now = 2_000_000_000; let stats = DiffStat { files_changed: 1, insertions: 2, deletions: 3, }; let mut slot = CommitSlot { commit: Commit { id: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(), summary: "Summary".to_owned(), author: "Alice".to_owned(), branches: vec!["main".to_owned()], recency: CommitTime { seconds: now - 3_600, }, stats, }, progress: ReviewProgress { accepted: 0, total: 1, }, accepted_hunks: 0, total_hunks: 1, comment_count: 3, state: CommitReviewState::Pending, remaining_stats: stats, document: None, identities: None, loaded: None, }; for (state, marker) in [ (CommitReviewState::Accepted, REVIEWED_MARK), (CommitReviewState::Rejected, REJECTED_MARK), ] { slot.state = state; assert_eq!( commit_row(&slot, DiffPalette::default())[0].to_string(), marker.to_string() ); assert!( commit_row_suffix( &slot, DiffPalette::default(), now as u64, stats.insertions + stats.deletions, 8, )[5] .to_string() .is_empty() ); } slot.state = CommitReviewState::Dropped; let [hunks, mut author, mut age, _, comments, diffstat] = commit_row_suffix( &slot, DiffPalette::default(), now as u64, stats.insertions + stats.deletions, 8, ); assert_eq!( commit_row(&slot, DiffPalette::default())[0].to_string(), DROPPED_MARK.to_string() ); assert!(diffstat.to_string().is_empty()); assert_eq!(hunks.to_string(), "0%/1 "); assert_eq!(comments.to_string(), "🗩 3"); let mut author_buffer = Buffer::empty(Rect::new(0, 0, slot.commit.author.len(), 1)); let mut age_buffer = Buffer::empty(Rect::new(0, 0, 16, 1)); author.render(author_buffer.area(), &mut author_buffer); age.render(age_buffer.area(), &mut age_buffer); assert_eq!( author_buffer.get(0, 0).unwrap().style(), Style::default().fg(HISTORY_VALUE_FG).dim().strikethrough() ); assert_eq!( age_buffer.get(0, 0).unwrap().style(), Style::default() .fg(colors::fixed::MUTED) .dim() .strikethrough() ); slot.state = CommitReviewState::Pending; assert_eq!( commit_row(&slot, DiffPalette::default())[0].to_string(), PENDING_MARK.to_string() ); slot.accepted_hunks = 1; assert_eq!( commit_row(&slot, DiffPalette::default())[0].to_string(), IN_PROGRESS_MARK.to_string() ); for (state, accepted_hunks, expected_color) in [ (CommitReviewState::Pending, 0, colors::fixed::MUTED), (CommitReviewState::Pending, 1, colors::rgb::ORANGE), ( CommitReviewState::Pending, 2, DiffPalette::default().positive_fg, ), ( CommitReviewState::Rejected, 0, DiffPalette::default().negative_fg, ), ] { slot.state = state; slot.accepted_hunks = accepted_hunks; slot.total_hunks = 2; let [mut hunks, _, _, _, _, _] = commit_row_suffix( &slot, DiffPalette::default(), now as u64, stats.insertions + stats.deletions, 8, ); let mut buffer = Buffer::empty(Rect::new(0, 0, 16, 1)); hunks.render(buffer.area(), &mut buffer); assert_eq!( buffer.get(0, 0).unwrap().style(), Style::default().fg(expected_color) ); } } #[test] fn history_diffstat_scales_against_largest_commit() { let palette = DiffPalette::default(); let largest = DiffStat { files_changed: 1, insertions: 6, deletions: 4, }; let smaller = DiffStat { files_changed: 1, insertions: 2, deletions: 3, }; let deletion = DiffStat { files_changed: 1, insertions: 999, deletions: 1, }; let small_mixed = DiffStat { files_changed: 1, insertions: 1, deletions: 1, }; assert_eq!( history_diffstat(largest, 10, 8, palette).to_string(), "10 +++++---" ); assert_eq!( history_diffstat(smaller, 10, 8, palette).to_string(), " 5 ++--" ); assert_eq!( history_diffstat(deletion, 1_000, 8, palette).to_string(), "1000 +++++++-" ); assert_eq!( history_diffstat(small_mixed, 1_000, 8, palette).to_string(), " 2 +-" ); let wide = history_diffstat(largest, 10, 32, palette).to_string(); let uncapped = history_diffstat(largest, 10, 64, palette).to_string(); assert_eq!(wide.chars().count(), 35); assert!(uncapped.chars().count() > wide.chars().count()); } #[test] fn comment_card_lines_render_a_bordered_comment_card() { let comment = Comment { id: 1.into(), author: "alice".to_owned(), timestamp: current_timestamp(), body: "first\nsecond".to_owned(), }; let lines = comment_card_lines(&comment, true, 40); let text = lines .iter() .map(ToString::to_string) .collect::>() .join("\n"); assert_eq!(lines.len(), COMMENT_CARD_ROWS); assert!(text.contains("alice"), "text: {text:?}"); assert!(text.contains("just now"), "text: {text:?}"); assert!(text.contains("first second"), "text: {text:?}"); assert!(!text.contains('🗨'), "text: {text:?}"); } #[test] fn relative_time_uses_largest_whole_unit() { let now = 2_000_000_000; assert_eq!(relative_time(now, now), "just now"); assert_eq!(relative_time(now - 60, now), "1 minute ago"); assert_eq!(relative_time(now - 3_600, now), "1 hour ago"); assert_eq!(relative_time(now - 86_400, now), "1 day ago"); assert_eq!(relative_time(now - 2_592_000, now), "1 month ago"); assert_eq!(relative_time(now - 31_536_000, now), "1 year ago"); } #[test] fn relative_time_preserves_future_direction() { let now = 2_000_000_000; assert_eq!(relative_time(now + 1, now), "in less than a minute"); assert_eq!(relative_time(now + 60, now), "in 1 minute"); assert_eq!(relative_time(now + 7_200, now), "in 2 hours"); } }