crates/brain/src/session/hunk.rs 15.5 KiB raw
1
//! Hunk comment editor view.
2
3
use rustik_diff::{DiffAction, DiffViewer, HunkId};
4
use rustik_tui::{
5
    Buffer, Color, Constraint, Line, Rect, RenderResult, Scroll, Size, StatefulWidget, Style,
6
    TextField, TextInput, Widget,
7
};
8
9
use super::status::{
10
    COMMENT_CARD_CHROME_COLS, COMMENT_CARD_CHROME_ROWS, COMMENT_CARD_ROWS, comment_age,
11
    comment_card_lines, comment_editor_lines,
12
};
13
use crate::comments::{Comment, CommentId};
14
15
/// Maximum rows the comment input grows to.
16
const MAX_INPUT_ROWS: usize = 6;
17
/// Maximum rows used to list a hunk's existing comments.
18
const MAX_COMMENT_ROWS: usize = 8;
19
/// Comment editor target.
20
#[derive(Clone, Debug, Eq, PartialEq)]
21
pub(super) enum CommentEdit {
22
    /// Add a new comment.
23
    Add,
24
    /// Edit an existing comment.
25
    Edit(CommentId),
26
}
27
28
/// Active hunk comment mode.
29
#[derive(Clone, Debug)]
30
enum HunkMode {
31
    /// Browse existing comments and hunk content.
32
    Browsing {
33
        /// Selected comment row.
34
        selected: usize,
35
    },
36
    /// Edit a new or existing comment.
37
    Editing {
38
        /// Selected comment row before entering edit mode.
39
        selected: usize,
40
        /// Comment being edited.
41
        target: CommentEdit,
42
        /// Comment text being authored.
43
        input: TextInput,
44
    },
45
}
46
47
/// State for the hunk view: the hunk, its isolated viewer, and the in-progress
48
/// comment.
49
#[derive(Debug)]
50
pub(super) struct HunkView {
51
    /// Hunk being commented on.
52
    pub(super) hunk: HunkId,
53
    /// Viewer rendering the single hunk in isolation.
54
    pub(super) viewer: DiffViewer,
55
    /// Author shown for newly authored draft comments.
56
    author: String,
57
    /// Current comment mode.
58
    mode: HunkMode,
59
    /// Whether the first render still needs to reveal the hunk's final rows.
60
    scroll_to_bottom: bool,
61
}
62
63
impl HunkView {
64
    /// Creates a hunk comment view.
65
    pub(super) fn new(hunk: HunkId, viewer: DiffViewer, author: String) -> Self {
66
        Self {
67
            hunk,
68
            viewer,
69
            author,
70
            mode: HunkMode::Browsing { selected: 0 },
71
            scroll_to_bottom: true,
72
        }
73
    }
74
75
    /// Returns whether the view is editing a comment.
76
    pub(super) fn is_editing(&self) -> bool {
77
        matches!(self.mode, HunkMode::Editing { .. })
78
    }
79
80
    /// Starts a new comment draft.
81
    pub(super) fn enter(&mut self) {
82
        self.mode = HunkMode::Editing {
83
            selected: self.selected(),
84
            target: CommentEdit::Add,
85
            input: TextInput::new(),
86
        };
87
    }
88
89
    /// Starts editing `comment`.
90
    pub(super) fn start_edit(&mut self, comment: &Comment) {
91
        self.mode = HunkMode::Editing {
92
            selected: self.selected(),
93
            target: CommentEdit::Edit(comment.id.clone()),
94
            input: TextInput::with_value(comment.body.clone()),
95
        };
96
    }
97
98
    /// Cancels the active draft.
99
    pub(super) fn cancel_edit(&mut self) {
100
        self.mode = HunkMode::Browsing {
101
            selected: self.selected(),
102
        };
103
    }
104
105
    /// Returns the active non-empty draft without closing its editor.
106
    pub(super) fn pending_edit(&self) -> Option<(CommentEdit, String)> {
107
        let HunkMode::Editing { target, input, .. } = &self.mode else {
108
            return None;
109
        };
110
        if input.is_empty() {
111
            return None;
112
        }
113
        Some((target.clone(), input.value().to_owned()))
114
    }
115
116
    /// Applies an edit key to the draft comment.
117
    pub(super) fn input(&mut self, key: rustik_tui::Key) -> bool {
118
        let HunkMode::Editing { input, .. } = &mut self.mode else {
119
            return false;
120
        };
121
        input.input(key)
122
    }
123
124
    /// Inserts a newline into the draft comment.
125
    pub(super) fn newline(&mut self) -> bool {
126
        let HunkMode::Editing { input, .. } = &mut self.mode else {
127
            return false;
128
        };
129
        input.newline()
130
    }
131
132
    /// Returns the currently selected comment row.
133
    pub(super) fn selected(&self) -> usize {
134
        match &self.mode {
135
            HunkMode::Browsing { selected } => *selected,
136
            HunkMode::Editing { selected, .. } => *selected,
137
        }
138
    }
139
140
    /// Selects the next comment.
141
    pub(super) fn select_next(&mut self, comments: usize) {
142
        let HunkMode::Browsing { selected } = &mut self.mode else {
143
            return;
144
        };
145
        *selected = selected.saturating_add(1).min(comments.saturating_sub(1));
146
    }
147
148
    /// Selects the previous comment.
149
    pub(super) fn select_previous(&mut self) {
150
        let HunkMode::Browsing { selected } = &mut self.mode else {
151
            return;
152
        };
153
        *selected = selected.saturating_sub(1);
154
    }
155
156
    /// Clamps the selected comment after comment list changes.
157
    pub(super) fn clamp_selection(&mut self, comments: usize) {
158
        let HunkMode::Browsing { selected } = &mut self.mode else {
159
            return;
160
        };
161
        *selected = (*selected).min(comments.saturating_sub(1));
162
    }
163
164
    /// Selects a stored comment directly.
165
    pub(super) fn select_comment(&mut self, comment: usize) {
166
        let HunkMode::Browsing { selected } = &mut self.mode else {
167
            return;
168
        };
169
        *selected = comment;
170
    }
171
172
    /// Returns the area occupied by the isolated hunk viewer.
173
    pub(super) fn viewer_area(&self, area: Rect, comment_rows: usize) -> Rect {
174
        self.areas(area, comment_rows).0
175
    }
176
177
    /// Returns rendered rows needed for `comments` stored cards and the editor.
178
    ///
179
    /// A comment being edited is rendered as the editor card in its place, so
180
    /// it does not count towards the stored cards.
181
    pub(super) fn comment_rows(&self, comments: usize) -> usize {
182
        let stored = match &self.mode {
183
            HunkMode::Editing {
184
                target: CommentEdit::Edit(_),
185
                ..
186
            } => comments.saturating_sub(1),
187
            _ => comments,
188
        };
189
        (stored * COMMENT_CARD_ROWS).min(MAX_COMMENT_ROWS) + self.editor_rows()
190
    }
191
192
    /// Returns the number of table-body rows needed by the active editor.
193
    fn editor_body_rows(&self) -> usize {
194
        match &self.mode {
195
            HunkMode::Editing { input, .. } => {
196
                input.value().split('\n').count().clamp(1, MAX_INPUT_ROWS)
197
            }
198
            HunkMode::Browsing { .. } => 0,
199
        }
200
    }
201
202
    /// Returns the number of rendered rows needed by the active editor.
203
    fn editor_rows(&self) -> usize {
204
        if self.is_editing() {
205
            self.editor_body_rows() + COMMENT_CARD_CHROME_ROWS
206
        } else {
207
            0
208
        }
209
    }
210
211
    /// Returns the hunk and comment areas.
212
    fn areas(&self, area: Rect, comment_rows: usize) -> (Rect, Rect) {
213
        let comments_h = comment_rows.min(area.rows);
214
        let hunk_available = area.rows.saturating_sub(comments_h);
215
        let hunk_h = self
216
            .viewer
217
            .size(Constraint::max(Size::new(area.cols, hunk_available)))
218
            .rows
219
            .min(hunk_available);
220
221
        (
222
            Rect::new(area.x, area.y, area.cols, hunk_h),
223
            Rect::new(area.x, area.y + hunk_h, area.cols, comments_h),
224
        )
225
    }
226
}
227
228
impl HunkView {
229
    /// Returns lines for every comment card, swapping the edited card for the
230
    /// editor, and the editor card's row offset within them.
231
    ///
232
    /// Cards are windowed so the selected card stays visible with one card of
233
    /// context above it. Stored cards are capped at [`MAX_COMMENT_ROWS`]; a
234
    /// new-draft editor always follows them.
235
    fn comment_lines(&self, comments: &[Comment], cols: usize) -> (Vec<Line>, Option<usize>) {
236
        let selected = self.selected();
237
        let first = selected.saturating_sub(1);
238
        let editor_body_rows = self.editor_body_rows();
239
        let mut lines = Vec::new();
240
        let mut editor_row = None;
241
        let mut stored_rows = 0;
242
243
        for (index, comment) in comments.iter().enumerate().skip(first) {
244
            let edited = matches!(
245
                &self.mode,
246
                HunkMode::Editing { target: CommentEdit::Edit(id), .. } if *id == comment.id
247
            );
248
            if edited {
249
                editor_row = Some(lines.len());
250
                lines.extend(comment_editor_lines(
251
                    &comment.author,
252
                    &comment_age(comment),
253
                    editor_body_rows,
254
                    cols,
255
                ));
256
            } else if stored_rows < MAX_COMMENT_ROWS {
257
                let card =
258
                    comment_card_lines(comment, !self.is_editing() && index == selected, cols);
259
                let take = card.len().min(MAX_COMMENT_ROWS - stored_rows);
260
                stored_rows += take;
261
                lines.extend(card.into_iter().take(take));
262
            }
263
        }
264
        if matches!(
265
            &self.mode,
266
            HunkMode::Editing {
267
                target: CommentEdit::Add,
268
                ..
269
            }
270
        ) {
271
            editor_row = Some(lines.len());
272
            lines.extend(comment_editor_lines(
273
                &self.author,
274
                "just now",
275
                editor_body_rows,
276
                cols,
277
            ));
278
        }
279
280
        (lines, editor_row)
281
    }
282
}
283
284
impl StatefulWidget for HunkView {
285
    type State = Vec<Comment>;
286
287
    fn size(&self, parent: Constraint) -> Size {
288
        parent.bounded_size()
289
    }
290
291
    fn render_with_state(
292
        &mut self,
293
        area: rustik_tui::Rect,
294
        buf: &mut Buffer,
295
        comments: &mut Self::State,
296
    ) -> RenderResult {
297
        if area.is_empty() {
298
            return RenderResult::default();
299
        }
300
        self.clamp_selection(comments.len());
301
        let (hunk_area, comments_area) = self.areas(area, self.comment_rows(comments.len()));
302
        let mut result = RenderResult::default();
303
        if self.scroll_to_bottom {
304
            self.viewer
305
                .apply(DiffAction::Scroll(Scroll::Bottom), hunk_area);
306
            self.scroll_to_bottom = false;
307
        }
308
309
        self.viewer.render(hunk_area, buf);
310
311
        let (lines, editor_row) = self.comment_lines(comments, comments_area.cols);
312
        Line::renders(
313
            lines.into_iter().take(comments_area.rows),
314
            comments_area,
315
            buf,
316
        );
317
318
        // The editable body sits below the edited card's top border and header
319
        // row, inset past the side borders.
320
        let editor_body_rows = self.editor_body_rows();
321
        if let (Some(row), HunkMode::Editing { input, .. }) = (editor_row, &mut self.mode) {
322
            let card_rows = comments_area.rows.saturating_sub(row);
323
            let body_area = Rect::new(
324
                comments_area.x.saturating_add(COMMENT_CARD_CHROME_COLS),
325
                comments_area.y + row + COMMENT_CARD_CHROME_ROWS - 1,
326
                comments_area
327
                    .cols
328
                    .saturating_sub(2 * COMMENT_CARD_CHROME_COLS),
329
                editor_body_rows.min(card_rows.saturating_sub(COMMENT_CARD_CHROME_ROWS)),
330
            );
331
            if !body_area.is_empty() {
332
                result = TextField::new()
333
                    .style(Style::default().fg(Color::White))
334
                    .placeholder("Write a comment...")
335
                    .render_with_state(body_area, buf, input);
336
            }
337
        }
338
339
        result
340
    }
341
}
342
343
#[cfg(test)]
344
mod tests {
345
    use rustik_diff::{Decode as _, DiffDocument, DiffOptions, FileTreeMode};
346
347
    use super::*;
348
349
    fn hunk_view() -> HunkView {
350
        let document = DiffDocument::decode_str(
351
            "\
352
diff --git a/a.txt b/a.txt
353
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
354
--- a/a.txt
355
+++ b/a.txt
356
@@ -1 +1 @@
357
-old
358
+new
359
",
360
        )
361
        .unwrap();
362
        let hunk = document.files[0].hunks[0].id;
363
        let viewer = DiffViewer::new(
364
            document,
365
            DiffOptions {
366
                file_tree: FileTreeMode::Hidden,
367
                ..DiffOptions::default()
368
            },
369
        );
370
371
        HunkView::new(hunk, viewer, "alice".to_owned())
372
    }
373
374
    #[test]
375
    fn editing_without_stored_comments_renders_card_and_cursor_below_hunk() {
376
        let area = Rect::new(0, 0, 60, 12);
377
        let mut view = hunk_view();
378
        view.enter();
379
        let hunk_area = view.viewer_area(area, view.comment_rows(0));
380
        let mut buffer = Buffer::empty(area);
381
        let mut comments = Vec::new();
382
383
        let result = view.render_with_state(area, &mut buffer, &mut comments);
384
        let text = buffer.lines().join("\n");
385
        let cursor = result.cursor.unwrap();
386
387
        assert!(text.contains("alice just now"), "text: {text:?}");
388
389
        assert!(text.contains("Write a comment..."), "text: {text:?}");
390
        assert_eq!(cursor.x, 2);
391
        assert!(
392
            cursor.y >= hunk_area.y + hunk_area.rows,
393
            "cursor: {cursor:?}"
394
        );
395
    }
396
    #[test]
397
    fn initial_editor_view_reveals_the_hunk_bottom() {
398
        let area = Rect::new(0, 0, 60, 8);
399
        let mut view = hunk_view();
400
        view.enter();
401
        let mut buffer = Buffer::empty(area);
402
        let mut comments = Vec::new();
403
404
        view.render_with_state(area, &mut buffer, &mut comments);
405
406
        assert!(view.viewer.state().scroll.offset > 0);
407
        assert!(buffer.lines().join("\n").contains("Write a comment..."));
408
    }
409
410
    #[test]
411
    fn editing_a_stored_comment_renders_the_editor_in_its_place() {
412
        let area = Rect::new(0, 0, 60, 16);
413
        let mut view = hunk_view();
414
        let mut comments = vec![
415
            Comment {
416
                id: 1.into(),
417
                author: "alice".to_owned(),
418
                timestamp: 0,
419
                body: "first".to_owned(),
420
            },
421
            Comment {
422
                id: 2.into(),
423
                author: "bob".to_owned(),
424
                timestamp: 0,
425
                body: "second".to_owned(),
426
            },
427
        ];
428
        view.start_edit(&comments[0]);
429
        let mut buffer = Buffer::empty(area);
430
431
        let result = view.render_with_state(area, &mut buffer, &mut comments);
432
        let text = buffer.lines().join("\n");
433
        let cursor = result.cursor.unwrap();
434
435
        // The edited comment appears once, as the editor card, above the
436
        // untouched second card.
437
        assert_eq!(text.matches("alice").count(), 1, "text: {text:?}");
438
        assert_eq!(text.matches("first").count(), 1, "text: {text:?}");
439
        assert!(text.contains("bob"), "text: {text:?}");
440
        let alice_row = buffer
441
            .lines()
442
            .iter()
443
            .position(|line| line.contains("alice"))
444
            .unwrap();
445
        let bob_row = buffer
446
            .lines()
447
            .iter()
448
            .position(|line| line.contains("bob"))
449
            .unwrap();
450
        assert!(alice_row < bob_row);
451
        // The cursor sits on the edited card's body row, after the prefilled
452
        // text.
453
        assert_eq!(cursor.y, alice_row + 1);
454
        assert_eq!(cursor.x, 2 + "first".len());
455
    }
456
    #[test]
457
    fn comment_input_handles_navigation_keys() {
458
        let mut view = hunk_view();
459
        view.enter();
460
        assert!(view.input(rustik_tui::Key::Char('a')));
461
        assert!(view.newline());
462
        assert!(view.input(rustik_tui::Key::Char('b')));
463
        assert!(view.input(rustik_tui::Key::Up));
464
        assert!(view.input(rustik_tui::Key::Home));
465
        assert!(view.input(rustik_tui::Key::Char('x')));
466
467
        assert_eq!(view.pending_edit().unwrap().1, "xa\nb");
468
    }
469
470
    #[test]
471
    fn failed_comment_save_keeps_active_editor() {
472
        let mut view = hunk_view();
473
        view.enter();
474
        assert!(view.input(rustik_tui::Key::Char('x')));
475
476
        let draft = view.pending_edit().unwrap();
477
        let persistence = Err::<(), _>("write failed");
478
479
        assert_eq!(draft.1, "x");
480
        assert!(persistence.is_err());
481
        assert!(view.is_editing());
482
    }
483
}