//! Hunk comment editor view. use rustik_diff::{DiffAction, DiffViewer, HunkId}; use rustik_tui::{ Buffer, Color, Constraint, Line, Rect, RenderResult, Scroll, Size, StatefulWidget, Style, TextField, TextInput, Widget, }; use super::status::{ COMMENT_CARD_CHROME_COLS, COMMENT_CARD_CHROME_ROWS, comment_age, comment_card_lines, comment_editor_lines, }; use crate::comments::{Comment, CommentId}; /// Maximum rows the comment input grows to. const MAX_INPUT_ROWS: usize = 6; /// Maximum rows used to list a hunk's existing comments. const MAX_COMMENT_ROWS: usize = 8; /// Comment editor target. #[derive(Clone, Debug, Eq, PartialEq)] pub(super) enum CommentEdit { /// Add a new comment. Add, /// Edit an existing comment. Edit(CommentId), } /// Active hunk comment mode. #[derive(Clone, Debug)] enum HunkMode { /// Browse existing comments and hunk content. Browsing { /// Selected comment row. selected: usize, }, /// Edit a new or existing comment. Editing { /// Selected comment row before entering edit mode. selected: usize, /// Comment being edited. target: CommentEdit, /// Comment text being authored. input: TextInput, }, } /// State for the hunk view: the hunk, its isolated viewer, and the in-progress /// comment. #[derive(Debug)] pub(super) struct HunkView { /// Hunk being commented on. pub(super) hunk: HunkId, /// Viewer rendering the single hunk in isolation. pub(super) viewer: DiffViewer, /// Author shown for newly authored draft comments. author: String, /// Current comment mode. mode: HunkMode, /// Whether the first render still needs to reveal the hunk's final rows. scroll_to_bottom: bool, } impl HunkView { /// Creates a hunk comment view. pub(super) fn new(hunk: HunkId, viewer: DiffViewer, author: String) -> Self { Self { hunk, viewer, author, mode: HunkMode::Browsing { selected: 0 }, scroll_to_bottom: true, } } /// Returns whether the view is editing a comment. pub(super) fn is_editing(&self) -> bool { matches!(self.mode, HunkMode::Editing { .. }) } /// Starts a new comment draft. pub(super) fn enter(&mut self) { self.mode = HunkMode::Editing { selected: self.selected(), target: CommentEdit::Add, input: TextInput::new(), }; } /// Starts editing `comment`. pub(super) fn start_edit(&mut self, comment: &Comment) { self.mode = HunkMode::Editing { selected: self.selected(), target: CommentEdit::Edit(comment.id.clone()), input: TextInput::with_value(comment.body.clone()), }; } /// Cancels the active draft. pub(super) fn cancel_edit(&mut self) { self.mode = HunkMode::Browsing { selected: self.selected(), }; } /// Returns the active non-empty draft without closing its editor. pub(super) fn pending_edit(&self) -> Option<(CommentEdit, String)> { let HunkMode::Editing { target, input, .. } = &self.mode else { return None; }; if input.is_empty() { return None; } Some((target.clone(), input.value().to_owned())) } /// Applies an edit key to the draft comment. pub(super) fn input(&mut self, key: rustik_tui::Key) -> bool { let HunkMode::Editing { input, .. } = &mut self.mode else { return false; }; input.input(key) } /// Inserts a newline into the draft comment. pub(super) fn newline(&mut self) -> bool { let HunkMode::Editing { input, .. } = &mut self.mode else { return false; }; input.newline() } /// Returns the currently selected comment row. pub(super) fn selected(&self) -> usize { match &self.mode { HunkMode::Browsing { selected } => *selected, HunkMode::Editing { selected, .. } => *selected, } } /// Selects the next comment. pub(super) fn select_next(&mut self, comments: usize) { let HunkMode::Browsing { selected } = &mut self.mode else { return; }; *selected = selected.saturating_add(1).min(comments.saturating_sub(1)); } /// Selects the previous comment. pub(super) fn select_previous(&mut self) { let HunkMode::Browsing { selected } = &mut self.mode else { return; }; *selected = selected.saturating_sub(1); } /// Clamps the selected comment after comment list changes. pub(super) fn clamp_selection(&mut self, comments: usize) { let HunkMode::Browsing { selected } = &mut self.mode else { return; }; *selected = (*selected).min(comments.saturating_sub(1)); } /// Selects a stored comment directly. pub(super) fn select_comment(&mut self, comment: usize) { let HunkMode::Browsing { selected } = &mut self.mode else { return; }; *selected = comment; } /// Returns the area occupied by the isolated hunk viewer. pub(super) fn viewer_area(&self, area: Rect, comment_rows: usize) -> Rect { self.areas(area, comment_rows).0 } /// Returns rendered rows needed for stored cards and the editor. /// /// A comment being edited is rendered as the editor card in its place, so /// it does not count towards the stored cards. pub(super) fn comment_rows(&self, comments: &[Comment]) -> usize { let edited = match &self.mode { HunkMode::Editing { target: CommentEdit::Edit(id), .. } => Some(id), _ => None, }; let stored = comments .iter() .filter(|comment| edited != Some(&comment.id)) .map(|comment| COMMENT_CARD_CHROME_ROWS + comment.body.lines().count().max(1)) .sum::(); stored.min(MAX_COMMENT_ROWS) + self.editor_rows() } /// Returns the number of table-body rows needed by the active editor. fn editor_body_rows(&self) -> usize { match &self.mode { HunkMode::Editing { input, .. } => { input.value().split('\n').count().clamp(1, MAX_INPUT_ROWS) } HunkMode::Browsing { .. } => 0, } } /// Returns the number of rendered rows needed by the active editor. fn editor_rows(&self) -> usize { if self.is_editing() { self.editor_body_rows() + COMMENT_CARD_CHROME_ROWS } else { 0 } } /// Returns the hunk and comment areas. fn areas(&self, area: Rect, comment_rows: usize) -> (Rect, Rect) { let comments_h = comment_rows.min(area.rows); let hunk_available = area.rows.saturating_sub(comments_h); let hunk_h = self .viewer .size(Constraint::max(Size::new(area.cols, hunk_available))) .rows .min(hunk_available); ( Rect::new(area.x, area.y, area.cols, hunk_h), Rect::new(area.x, area.y + hunk_h, area.cols, comments_h), ) } } impl HunkView { /// Returns lines for every comment card, swapping the edited card for the /// editor, and the editor card's row offset within them. /// /// Cards are windowed so the selected card stays visible with one card of /// context above it. Stored cards are capped at [`MAX_COMMENT_ROWS`]; a /// new-draft editor always follows them. fn comment_lines(&self, comments: &[Comment], cols: usize) -> (Vec, Option) { let selected = self.selected(); let first = selected.saturating_sub(1); let editor_body_rows = self.editor_body_rows(); let mut lines = Vec::new(); let mut editor_row = None; let mut stored_rows = 0; for (index, comment) in comments.iter().enumerate().skip(first) { let edited = matches!( &self.mode, HunkMode::Editing { target: CommentEdit::Edit(id), .. } if *id == comment.id ); if edited { editor_row = Some(lines.len()); lines.extend(comment_editor_lines( &comment.author, &comment_age(comment), editor_body_rows, cols, )); } else if stored_rows < MAX_COMMENT_ROWS { let card = comment_card_lines(comment, !self.is_editing() && index == selected, cols); let take = card.len().min(MAX_COMMENT_ROWS - stored_rows); stored_rows += take; lines.extend(card.into_iter().take(take)); } } if matches!( &self.mode, HunkMode::Editing { target: CommentEdit::Add, .. } ) { editor_row = Some(lines.len()); lines.extend(comment_editor_lines( &self.author, "just now", editor_body_rows, cols, )); } (lines, editor_row) } } impl StatefulWidget for HunkView { type State = Vec; fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render_with_state( &mut self, area: rustik_tui::Rect, buf: &mut Buffer, comments: &mut Self::State, ) -> RenderResult { if area.is_empty() { return RenderResult::default(); } self.clamp_selection(comments.len()); let (hunk_area, comments_area) = self.areas(area, self.comment_rows(comments)); let mut result = RenderResult::default(); if self.scroll_to_bottom { self.viewer .apply(DiffAction::Scroll(Scroll::Bottom), hunk_area); self.scroll_to_bottom = false; } self.viewer.render(hunk_area, buf); let (lines, editor_row) = self.comment_lines(comments, comments_area.cols); Line::renders( lines.into_iter().take(comments_area.rows), comments_area, buf, ); // The editable body sits below the edited card's top border and header // row, inset past the side borders. let editor_body_rows = self.editor_body_rows(); if let (Some(row), HunkMode::Editing { input, .. }) = (editor_row, &mut self.mode) { let card_rows = comments_area.rows.saturating_sub(row); let body_area = Rect::new( comments_area.x.saturating_add(COMMENT_CARD_CHROME_COLS), comments_area.y + row + COMMENT_CARD_CHROME_ROWS - 1, comments_area .cols .saturating_sub(2 * COMMENT_CARD_CHROME_COLS), editor_body_rows.min(card_rows.saturating_sub(COMMENT_CARD_CHROME_ROWS)), ); if !body_area.is_empty() { result = TextField::new() .style(Style::default().fg(Color::White)) .placeholder("Write a comment...") .render_with_state(body_area, buf, input); } } result } } #[cfg(test)] mod tests { use rustik_diff::{Decode as _, DiffDocument, DiffOptions, FileTreeMode}; use super::*; fn hunk_view() -> HunkView { let document = DiffDocument::decode_str( "\ diff --git a/a.txt b/a.txt index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.txt +++ b/a.txt @@ -1 +1 @@ -old +new ", ) .unwrap(); let hunk = document.files[0].hunks[0].id; let viewer = DiffViewer::new( document, DiffOptions { file_tree: FileTreeMode::Hidden, ..DiffOptions::default() }, ); HunkView::new(hunk, viewer, "alice".to_owned()) } #[test] fn editing_without_stored_comments_renders_card_and_cursor_below_hunk() { let area = Rect::new(0, 0, 60, 12); let mut view = hunk_view(); view.enter(); let hunk_area = view.viewer_area(area, view.comment_rows(&[])); let mut buffer = Buffer::empty(area); let mut comments = Vec::new(); let result = view.render_with_state(area, &mut buffer, &mut comments); let text = buffer.lines().join("\n"); let cursor = result.cursor.unwrap(); assert!(text.contains("alice just now"), "text: {text:?}"); assert!(text.contains("Write a comment..."), "text: {text:?}"); assert_eq!(cursor.x, 2); assert!( cursor.y >= hunk_area.y + hunk_area.rows, "cursor: {cursor:?}" ); } #[test] fn initial_editor_view_reveals_the_hunk_bottom() { let area = Rect::new(0, 0, 60, 8); let mut view = hunk_view(); view.enter(); let mut buffer = Buffer::empty(area); let mut comments = Vec::new(); view.render_with_state(area, &mut buffer, &mut comments); assert!(view.viewer.state().scroll.offset > 0); assert!(buffer.lines().join("\n").contains("Write a comment...")); } #[test] fn editing_a_stored_comment_renders_the_editor_in_its_place() { let area = Rect::new(0, 0, 60, 16); let mut view = hunk_view(); let mut comments = vec![ Comment { id: 1.into(), author: "alice".to_owned(), timestamp: 0, body: "first".to_owned(), }, Comment { id: 2.into(), author: "bob".to_owned(), timestamp: 0, body: "second".to_owned(), }, ]; view.start_edit(&comments[0]); let mut buffer = Buffer::empty(area); let result = view.render_with_state(area, &mut buffer, &mut comments); let text = buffer.lines().join("\n"); let cursor = result.cursor.unwrap(); // The edited comment appears once, as the editor card, above the // untouched second card. assert_eq!(text.matches("alice").count(), 1, "text: {text:?}"); assert_eq!(text.matches("first").count(), 1, "text: {text:?}"); assert!(text.contains("bob"), "text: {text:?}"); let alice_row = buffer .lines() .iter() .position(|line| line.contains("alice")) .unwrap(); let bob_row = buffer .lines() .iter() .position(|line| line.contains("bob")) .unwrap(); assert!(alice_row < bob_row); // The cursor sits on the edited card's body row, after the prefilled // text. assert_eq!(cursor.y, alice_row + 1); assert_eq!(cursor.x, 2 + "first".len()); } #[test] fn comment_input_handles_navigation_keys() { let mut view = hunk_view(); view.enter(); assert!(view.input(rustik_tui::Key::Char('a'))); assert!(view.newline()); assert!(view.input(rustik_tui::Key::Char('b'))); assert!(view.input(rustik_tui::Key::Up)); assert!(view.input(rustik_tui::Key::Home)); assert!(view.input(rustik_tui::Key::Char('x'))); assert_eq!(view.pending_edit().unwrap().1, "xa\nb"); } #[test] fn failed_comment_save_keeps_active_editor() { let mut view = hunk_view(); view.enter(); assert!(view.input(rustik_tui::Key::Char('x'))); let draft = view.pending_edit().unwrap(); let persistence = Err::<(), _>("write failed"); assert_eq!(draft.1, "x"); assert!(persistence.is_err()); assert!(view.is_editing()); } }