crates/brain/src/session/hunk.rs 15.6 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_age, comment_card_lines,
11
    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 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: &[Comment]) -> usize {
182
        let edited = match &self.mode {
183
            HunkMode::Editing {
184
                target: CommentEdit::Edit(id),
185
                ..
186
            } => Some(id),
187
            _ => None,
188
        };
189
        let stored = comments
190
            .iter()
191
            .filter(|comment| edited != Some(&comment.id))
192
            .map(|comment| COMMENT_CARD_CHROME_ROWS + comment.body.lines().count().max(1))
193
            .sum::<usize>();
194
        stored.min(MAX_COMMENT_ROWS) + self.editor_rows()
195
    }
196
197
    /// Returns the number of table-body rows needed by the active editor.
198
    fn editor_body_rows(&self) -> usize {
199
        match &self.mode {
200
            HunkMode::Editing { input, .. } => {
201
                input.value().split('\n').count().clamp(1, MAX_INPUT_ROWS)
202
            }
203
            HunkMode::Browsing { .. } => 0,
204
        }
205
    }
206
207
    /// Returns the number of rendered rows needed by the active editor.
208
    fn editor_rows(&self) -> usize {
209
        if self.is_editing() {
210
            self.editor_body_rows() + COMMENT_CARD_CHROME_ROWS
211
        } else {
212
            0
213
        }
214
    }
215
216
    /// Returns the hunk and comment areas.
217
    fn areas(&self, area: Rect, comment_rows: usize) -> (Rect, Rect) {
218
        let comments_h = comment_rows.min(area.rows);
219
        let hunk_available = area.rows.saturating_sub(comments_h);
220
        let hunk_h = self
221
            .viewer
222
            .size(Constraint::max(Size::new(area.cols, hunk_available)))
223
            .rows
224
            .min(hunk_available);
225
226
        (
227
            Rect::new(area.x, area.y, area.cols, hunk_h),
228
            Rect::new(area.x, area.y + hunk_h, area.cols, comments_h),
229
        )
230
    }
231
}
232
233
impl HunkView {
234
    /// Returns lines for every comment card, swapping the edited card for the
235
    /// editor, and the editor card's row offset within them.
236
    ///
237
    /// Cards are windowed so the selected card stays visible with one card of
238
    /// context above it. Stored cards are capped at [`MAX_COMMENT_ROWS`]; a
239
    /// new-draft editor always follows them.
240
    fn comment_lines(&self, comments: &[Comment], cols: usize) -> (Vec<Line>, Option<usize>) {
241
        let selected = self.selected();
242
        let first = selected.saturating_sub(1);
243
        let editor_body_rows = self.editor_body_rows();
244
        let mut lines = Vec::new();
245
        let mut editor_row = None;
246
        let mut stored_rows = 0;
247
248
        for (index, comment) in comments.iter().enumerate().skip(first) {
249
            let edited = matches!(
250
                &self.mode,
251
                HunkMode::Editing { target: CommentEdit::Edit(id), .. } if *id == comment.id
252
            );
253
            if edited {
254
                editor_row = Some(lines.len());
255
                lines.extend(comment_editor_lines(
256
                    &comment.author,
257
                    &comment_age(comment),
258
                    editor_body_rows,
259
                    cols,
260
                ));
261
            } else if stored_rows < MAX_COMMENT_ROWS {
262
                let card =
263
                    comment_card_lines(comment, !self.is_editing() && index == selected, cols);
264
                let take = card.len().min(MAX_COMMENT_ROWS - stored_rows);
265
                stored_rows += take;
266
                lines.extend(card.into_iter().take(take));
267
            }
268
        }
269
        if matches!(
270
            &self.mode,
271
            HunkMode::Editing {
272
                target: CommentEdit::Add,
273
                ..
274
            }
275
        ) {
276
            editor_row = Some(lines.len());
277
            lines.extend(comment_editor_lines(
278
                &self.author,
279
                "just now",
280
                editor_body_rows,
281
                cols,
282
            ));
283
        }
284
285
        (lines, editor_row)
286
    }
287
}
288
289
impl StatefulWidget for HunkView {
290
    type State = Vec<Comment>;
291
292
    fn size(&self, parent: Constraint) -> Size {
293
        parent.bounded_size()
294
    }
295
296
    fn render_with_state(
297
        &mut self,
298
        area: rustik_tui::Rect,
299
        buf: &mut Buffer,
300
        comments: &mut Self::State,
301
    ) -> RenderResult {
302
        if area.is_empty() {
303
            return RenderResult::default();
304
        }
305
        self.clamp_selection(comments.len());
306
        let (hunk_area, comments_area) = self.areas(area, self.comment_rows(comments));
307
        let mut result = RenderResult::default();
308
        if self.scroll_to_bottom {
309
            self.viewer
310
                .apply(DiffAction::Scroll(Scroll::Bottom), hunk_area);
311
            self.scroll_to_bottom = false;
312
        }
313
314
        self.viewer.render(hunk_area, buf);
315
316
        let (lines, editor_row) = self.comment_lines(comments, comments_area.cols);
317
        Line::renders(
318
            lines.into_iter().take(comments_area.rows),
319
            comments_area,
320
            buf,
321
        );
322
323
        // The editable body sits below the edited card's top border and header
324
        // row, inset past the side borders.
325
        let editor_body_rows = self.editor_body_rows();
326
        if let (Some(row), HunkMode::Editing { input, .. }) = (editor_row, &mut self.mode) {
327
            let card_rows = comments_area.rows.saturating_sub(row);
328
            let body_area = Rect::new(
329
                comments_area.x.saturating_add(COMMENT_CARD_CHROME_COLS),
330
                comments_area.y + row + COMMENT_CARD_CHROME_ROWS - 1,
331
                comments_area
332
                    .cols
333
                    .saturating_sub(2 * COMMENT_CARD_CHROME_COLS),
334
                editor_body_rows.min(card_rows.saturating_sub(COMMENT_CARD_CHROME_ROWS)),
335
            );
336
            if !body_area.is_empty() {
337
                result = TextField::new()
338
                    .style(Style::default().fg(Color::White))
339
                    .placeholder("Write a comment...")
340
                    .render_with_state(body_area, buf, input);
341
            }
342
        }
343
344
        result
345
    }
346
}
347
348
#[cfg(test)]
349
mod tests {
350
    use rustik_diff::{Decode as _, DiffDocument, DiffOptions, FileTreeMode};
351
352
    use super::*;
353
354
    fn hunk_view() -> HunkView {
355
        let document = DiffDocument::decode_str(
356
            "\
357
diff --git a/a.txt b/a.txt
358
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
359
--- a/a.txt
360
+++ b/a.txt
361
@@ -1 +1 @@
362
-old
363
+new
364
",
365
        )
366
        .unwrap();
367
        let hunk = document.files[0].hunks[0].id;
368
        let viewer = DiffViewer::new(
369
            document,
370
            DiffOptions {
371
                file_tree: FileTreeMode::Hidden,
372
                ..DiffOptions::default()
373
            },
374
        );
375
376
        HunkView::new(hunk, viewer, "alice".to_owned())
377
    }
378
379
    #[test]
380
    fn editing_without_stored_comments_renders_card_and_cursor_below_hunk() {
381
        let area = Rect::new(0, 0, 60, 12);
382
        let mut view = hunk_view();
383
        view.enter();
384
        let hunk_area = view.viewer_area(area, view.comment_rows(&[]));
385
        let mut buffer = Buffer::empty(area);
386
        let mut comments = Vec::new();
387
388
        let result = view.render_with_state(area, &mut buffer, &mut comments);
389
        let text = buffer.lines().join("\n");
390
        let cursor = result.cursor.unwrap();
391
392
        assert!(text.contains("alice just now"), "text: {text:?}");
393
394
        assert!(text.contains("Write a comment..."), "text: {text:?}");
395
        assert_eq!(cursor.x, 2);
396
        assert!(
397
            cursor.y >= hunk_area.y + hunk_area.rows,
398
            "cursor: {cursor:?}"
399
        );
400
    }
401
    #[test]
402
    fn initial_editor_view_reveals_the_hunk_bottom() {
403
        let area = Rect::new(0, 0, 60, 8);
404
        let mut view = hunk_view();
405
        view.enter();
406
        let mut buffer = Buffer::empty(area);
407
        let mut comments = Vec::new();
408
409
        view.render_with_state(area, &mut buffer, &mut comments);
410
411
        assert!(view.viewer.state().scroll.offset > 0);
412
        assert!(buffer.lines().join("\n").contains("Write a comment..."));
413
    }
414
415
    #[test]
416
    fn editing_a_stored_comment_renders_the_editor_in_its_place() {
417
        let area = Rect::new(0, 0, 60, 16);
418
        let mut view = hunk_view();
419
        let mut comments = vec![
420
            Comment {
421
                id: 1.into(),
422
                author: "alice".to_owned(),
423
                timestamp: 0,
424
                body: "first".to_owned(),
425
            },
426
            Comment {
427
                id: 2.into(),
428
                author: "bob".to_owned(),
429
                timestamp: 0,
430
                body: "second".to_owned(),
431
            },
432
        ];
433
        view.start_edit(&comments[0]);
434
        let mut buffer = Buffer::empty(area);
435
436
        let result = view.render_with_state(area, &mut buffer, &mut comments);
437
        let text = buffer.lines().join("\n");
438
        let cursor = result.cursor.unwrap();
439
440
        // The edited comment appears once, as the editor card, above the
441
        // untouched second card.
442
        assert_eq!(text.matches("alice").count(), 1, "text: {text:?}");
443
        assert_eq!(text.matches("first").count(), 1, "text: {text:?}");
444
        assert!(text.contains("bob"), "text: {text:?}");
445
        let alice_row = buffer
446
            .lines()
447
            .iter()
448
            .position(|line| line.contains("alice"))
449
            .unwrap();
450
        let bob_row = buffer
451
            .lines()
452
            .iter()
453
            .position(|line| line.contains("bob"))
454
            .unwrap();
455
        assert!(alice_row < bob_row);
456
        // The cursor sits on the edited card's body row, after the prefilled
457
        // text.
458
        assert_eq!(cursor.y, alice_row + 1);
459
        assert_eq!(cursor.x, 2 + "first".len());
460
    }
461
    #[test]
462
    fn comment_input_handles_navigation_keys() {
463
        let mut view = hunk_view();
464
        view.enter();
465
        assert!(view.input(rustik_tui::Key::Char('a')));
466
        assert!(view.newline());
467
        assert!(view.input(rustik_tui::Key::Char('b')));
468
        assert!(view.input(rustik_tui::Key::Up));
469
        assert!(view.input(rustik_tui::Key::Home));
470
        assert!(view.input(rustik_tui::Key::Char('x')));
471
472
        assert_eq!(view.pending_edit().unwrap().1, "xa\nb");
473
    }
474
475
    #[test]
476
    fn failed_comment_save_keeps_active_editor() {
477
        let mut view = hunk_view();
478
        view.enter();
479
        assert!(view.input(rustik_tui::Key::Char('x')));
480
481
        let draft = view.pending_edit().unwrap();
482
        let persistence = Err::<(), _>("write failed");
483
484
        assert_eq!(draft.1, "x");
485
        assert!(persistence.is_err());
486
        assert!(view.is_editing());
487
    }
488
}