diff: Add diff stats and fix minor style issues

fa048cae8f4f272263b913517746f463a1520f7c
Alexis Sellier committed ago 1 parent 9e17abe4
crates/diff/src/viewer.rs +17 -5
41 41
const SCROLLBAR_THUMB: char = '▓';
42 42
/// Scrollbar thumb color, one fixed-color shade darker than dim chrome.
43 43
const SCROLLBAR_THUMB_COLOR: Color = Color::Fixed(238);
44 44
/// File-card divider glyph (used between header/hunks and between hunks).
45 45
const DIVIDER: char = '─';
46 +
/// Foreground color for neutral file-kind badges such as moved and copied.
47 +
const FILE_KIND_BADGE_FG: Color = colors::rgb::PURPLE;
48 +
/// Dim background for neutral file-kind badges.
49 +
const FILE_KIND_BADGE_BG: Color = Color::RGB(32, 22, 42);
46 50
/// Shared border style for all file cards.
47 51
const FILE_BORDER: tui::Border = tui::Border::new(colors::FAINT);
48 52
/// Sticky file-header divider glyph.
49 53
const STICKY_DIVIDER: char = '╴';
50 54
/// Rename arrow.
51 -
const RENAME_ARROW: &str = "->";
55 +
const RENAME_ARROW: &str = "→";
52 56
/// Missing trailing newline marker.
53 57
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
54 58
/// Marker cell shown between hunks in the diff marker column.
55 59
const HUNK_GAP_MARKER_CELL: &str = " ⋮ ";
56 60
/// Default highlight lookahead after the visible viewport.
1643 1647
            FileKind::Deleted => Some(Self::change_badge(
1644 1648
                "deleted",
1645 1649
                palette.negative_fg,
1646 1650
                palette.negative_row_bg,
1647 1651
            )),
1648 -
            FileKind::Renamed => Some(Self::change_badge("moved", Color::Blue, Color::Fixed(236))),
1649 -
            FileKind::Copied => Some(Self::change_badge("copied", Color::Blue, Color::Fixed(236))),
1652 +
            FileKind::Renamed => Some(Self::change_badge(
1653 +
                "moved",
1654 +
                FILE_KIND_BADGE_FG,
1655 +
                FILE_KIND_BADGE_BG,
1656 +
            )),
1657 +
            FileKind::Copied => Some(Self::change_badge(
1658 +
                "copied",
1659 +
                FILE_KIND_BADGE_FG,
1660 +
                FILE_KIND_BADGE_BG,
1661 +
            )),
1650 1662
            FileKind::ModeChanged => Some(Self::change_badge(
1651 1663
                "mode changed",
1652 -
                Color::Blue,
1653 -
                Color::Fixed(236),
1664 +
                FILE_KIND_BADGE_FG,
1665 +
                FILE_KIND_BADGE_BG,
1654 1666
            )),
1655 1667
            FileKind::Binary => Some(Self::change_badge(
1656 1668
                "binary",
1657 1669
                Color::Yellow,
1658 1670
                Color::Fixed(236),
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/viewer/tree.rs +69 -19
3 3
use std::collections::BTreeSet;
4 4
use std::path::PathBuf;
5 5
6 6
use rustik_tui as tui;
7 7
use tui::{
8 -
    Buffer, Color, Label, Placement, Point, Rect, Style, Tree, TreeModel, TreeNodeKind, TreeRow,
9 -
    TreeState, TreeStyle, View,
8 +
    Buffer, Color, Label, Placement, Point, Rect, Style, Table, TableOptions, Tree, TreeModel,
9 +
    TreeNodeKind, TreeRow, TreeState, TreeStyle, View, Widget, colors,
10 10
};
11 11
12 -
use super::{DiffFocus, DiffPalette, DiffState, MIN_RENDER_COLS};
13 -
use crate::{DiffDocument, FileId, FileKind};
12 +
use super::{DiffFocus, DiffPalette, DiffState, FILE_KIND_BADGE_FG, MIN_RENDER_COLS};
13 +
use crate::{DiffDocument, FileId, FileKind, Stats};
14 14
15 15
/// Minimum columns reserved for the file tree when it is visible.
16 16
const DEFAULT_COLS: usize = 28;
17 17
/// Blank rows above the file tree list.
18 18
const TOP_PADDING_ROWS: usize = 1;
19 +
/// Rows reserved for the summary box below the file tree.
20 +
const INFO_BOX_ROWS: usize = 5;
21 +
/// Blank rows between the file tree and the summary box.
22 +
const INFO_BOX_GAP_ROWS: usize = 1;
23 +
/// Minimum tree rows kept visible when the summary box is shown.
24 +
const MIN_TREE_ROWS_WITH_INFO: usize = 3;
19 25
/// Background color for the current file-tree cursor row.
20 26
const CURSOR_BG: Color = Color::Fixed(235);
21 27
/// Background color for selected file-tree rows.
22 28
const SELECTED_BG: Color = Color::Fixed(234);
23 29
/// Foreground color for selected file-tree row labels.
146 152
        palette: DiffPalette,
147 153
        active: bool,
148 154
        area: Rect,
149 155
        buf: &mut Buffer,
150 156
    ) {
151 -
        let Some(area) = Self::body_area(area) else {
157 +
        let Some((tree_area, info_area)) = Self::areas(area) else {
152 158
            return;
153 159
        };
154 160
        let collapsed = self
155 161
            .model
156 162
            .branch_ids()
165 171
        let tree = Tree::new(&styled, &self.state)
166 172
            .active(active)
167 173
            .style(FILE_TREE_STYLE);
168 174
        let rows = tree.visible_rows();
169 175
        let row = tree.selected_row(&rows).unwrap_or_default();
170 -
        let view = View::new(0, rows.len(), area.rows).with_row_visible(row, Placement::Minimal);
171 -
172 -
        view.render_rows(area, buf, |row, cols| tree.render_row(rows[row], cols));
176 +
        let view =
177 +
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
178 +
179 +
        view.render_rows(tree_area, buf, |row, cols| tree.render_row(rows[row], cols));
180 +
        if let Some(area) = info_area {
181 +
            let mut table = Table::new(TableOptions {
182 +
                border: Some(tui::Border::new(colors::FAINT)),
183 +
                spacing: 2,
184 +
                ..TableOptions::default()
185 +
            });
186 +
            let stats = self.model.stats;
187 +
188 +
            table.push([
189 +
                Label::new("lines added").fg(FOLDER_FG),
190 +
                Label::from(format!("+{}", stats.insertions)).fg(palette.positive_fg),
191 +
            ]);
192 +
            table.push([
193 +
                Label::new("lines removed").fg(FOLDER_FG),
194 +
                Label::from(format!("-{}", stats.deletions)).fg(palette.negative_fg),
195 +
            ]);
196 +
            table.push([
197 +
                Label::new("files changed").fg(FOLDER_FG),
198 +
                Label::from(stats.files_changed.to_string()).fg(Color::White),
199 +
            ]);
200 +
            table.render(area, buf);
201 +
        }
173 202
    }
174 203
175 204
    /// Enters the file tree when it is visible.
176 205
    pub(super) fn enter(&mut self, selection: &FileSelection, focused_file: Option<FileId>) {
177 206
        if self.state.selected().is_none() {
190 219
        self.state.select_next(&self.model, delta);
191 220
    }
192 221
193 222
    /// Selects the file-tree row at `point` inside `area`.
194 223
    pub(super) fn select_at(&mut self, area: Rect, point: Point) -> bool {
195 -
        let Some(area) = Self::body_area(area) else {
224 +
        let Some((tree_area, _)) = Self::areas(area) else {
196 225
            return false;
197 226
        };
198 227
        let tree = Tree::new(&self.model, &self.state);
199 228
        let rows = tree.visible_rows();
200 229
        let row = tree.selected_row(&rows).unwrap_or_default();
201 -
        let view = View::new(0, rows.len(), area.rows).with_row_visible(row, Placement::Minimal);
202 -
        let Some(row) = view.row_at(area, point) else {
230 +
        let view =
231 +
            View::new(0, rows.len(), tree_area.rows).with_row_visible(row, Placement::Minimal);
232 +
        let Some(row) = view.row_at(tree_area, point) else {
203 233
            return false;
204 234
        };
205 235
        let Some(row) = rows.get(row) else {
206 236
            return false;
207 237
        };
326 356
            .next()
327 357
            .map(|row| row.id)
328 358
    }
329 359
330 360
    /// Returns the drawable row area for file-tree contents.
331 -
    fn body_area(area: Rect) -> Option<Rect> {
332 -
        let area = Rect::new(
361 +
    fn areas(area: Rect) -> Option<(Rect, Option<Rect>)> {
362 +
        let body: Rect = Rect::new(
333 363
            area.x,
334 364
            area.y.saturating_add(TOP_PADDING_ROWS),
335 365
            area.cols,
336 366
            area.rows.saturating_sub(TOP_PADDING_ROWS),
337 367
        );
338 -
        (!area.is_empty()).then_some(area)
368 +
        if body.is_empty() {
369 +
            return None;
370 +
        }
371 +
        let info_rows = INFO_BOX_ROWS + INFO_BOX_GAP_ROWS + MIN_TREE_ROWS_WITH_INFO;
372 +
        let info = (body.rows >= info_rows).then(|| {
373 +
            Rect::new(
374 +
                body.x,
375 +
                body.bottom().saturating_sub(INFO_BOX_ROWS),
376 +
                body.cols,
377 +
                INFO_BOX_ROWS,
378 +
            )
379 +
        });
380 +
        let tree_rows = if info.is_some() {
381 +
            body.rows.saturating_sub(INFO_BOX_ROWS + INFO_BOX_GAP_ROWS)
382 +
        } else {
383 +
            body.rows
384 +
        };
385 +
386 +
        Some((Rect::new(body.x, body.y, body.cols, tree_rows), info))
339 387
    }
340 388
}
341 389
342 390
/// Path tree built once from a diff document. Immutable after construction.
343 391
#[derive(Clone, Debug, Eq, PartialEq)]
344 392
pub(super) struct FileTreeModel {
345 393
    /// Root node ids.
346 394
    roots: Vec<usize>,
347 395
    /// Tree nodes indexed by id.
348 396
    nodes: Vec<FileTreeNode>,
397 +
    /// Aggregate diff statistics for the summary box.
398 +
    stats: Stats,
349 399
}
350 400
351 401
impl FileTreeModel {
352 402
    /// Creates a path tree from the files in `document`.
353 403
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
354 404
        let mut model = Self {
355 405
            roots: Vec::new(),
356 406
            nodes: Vec::new(),
407 +
            stats: document.stats(),
357 408
        };
358 409
        let root = model.push_node(None, root, None, FileTreeTarget::Root);
359 410
360 411
        for file in &document.files {
361 412
            model.insert_file(
615 666
            Color::White
616 667
        };
617 668
        let kind_fg = match file.kind {
618 669
            FileKind::Added => self.palette.positive_fg,
619 670
            FileKind::Deleted => self.palette.negative_fg,
620 -
            FileKind::Modified
621 -
            | FileKind::Renamed
622 -
            | FileKind::Copied
623 -
            | FileKind::ModeChanged
624 -
            | FileKind::Binary => Color::Yellow,
671 +
            FileKind::Renamed => FILE_KIND_BADGE_FG,
672 +
            FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
673 +
                Color::Yellow
674 +
            }
625 675
        };
626 676
627 677
        TreeRow::new(Label::new(&node.name).fg(fg))
628 678
            .marker(file.kind.marker())
629 679
            .marker_style(Style::new(kind_fg))
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden.rs +3 -3
163 163
}
164 164
165 165
#[test]
166 166
fn wide_file_tree_matches_golden_frame() {
167 167
    assert_golden(
168 -
        "wide_file_tree_100x8.txt",
169 -
        include_str!("golden/wide_file_tree_100x8.txt"),
168 +
        "wide_file_tree_100x12.txt",
169 +
        include_str!("golden/wide_file_tree_100x12.txt"),
170 170
        two_file_tree_viewer(),
171 171
        100,
172 -
        8,
172 +
        12,
173 173
    );
174 174
}
175 175
176 176
#[test]
177 177
fn file_tree_is_hidden_at_eighty_columns() {
crates/diff/tests/golden/file_kinds_80x24.txt +2 -2
7 7
│ ⊖ old.rs  deleted                                                        -1 │🮘
8 8
├─────────────────────────────────────────────────────────────────────────────┤🮘
9 9
│ 1          - old                                                            │🮘
10 10
╰─────────────────────────────────────────────────────────────────────────────╯🮘
11 11
╭─────────────────────────────────────────────────────────────────────────────╮🮘
12 -
│ ↦ from.rs -> to.rs  moved                                                   │🮘
12 +
│ ↦ from.rs → to.rs  moved                                                    │🮘
13 13
╰─────────────────────────────────────────────────────────────────────────────╯🮘
14 14
╭─────────────────────────────────────────────────────────────────────────────╮🮘
15 -
│ ⇉ copy.rs -> copy2.rs  copied                                               │🮘
15 +
│ ⇉ copy.rs → copy2.rs  copied                                                │🮘
16 16
╰─────────────────────────────────────────────────────────────────────────────╯🮘
17 17
╭─────────────────────────────────────────────────────────────────────────────╮🮘
18 18
│ ⊙ mode.sh  mode changed                                                     │🮘
19 19
╰─────────────────────────────────────────────────────────────────────────────╯🮘
20 20
╭─────────────────────────────────────────────────────────────────────────────╮🮘
crates/diff/tests/golden/wide_file_tree_100x12.txt added +12 -0
1 +
                             ╭────────────────────────────────────────────────────────────────────╮▓
2 +
▿ rustik/                    │ ⊙ a.rs                                                       +2 -1 │▓
3 +
  ⊙ a.rs                     ├────────────────────────────────────────────────────────────────────┤▓
4 +
  ⊙ b.rs                     │ 1    1       context                                               │▓
5 +
                             │ 2          - old                                                   │▓
6 +
                             │      2     + new                                                   │▓
7 +
                             │      3     + extra                                                 │▓
8 +
╭──────────────────────────╮ │ 3    4       tail                                                  │▓
9 +
│ lines added    +3        │ ╰────────────────────────────────────────────────────────────────────╯▓
10 +
│ lines removed  -2        │ ╭────────────────────────────────────────────────────────────────────╮🮘
11 +
│ files changed  2         │ │ ⊙ b.rs                                                       +1 -1 │🮘
12 +
╰──────────────────────────╯ ├────────────────────────────────────────────────────────────────────┤🮘
crates/diff/tests/golden/wide_file_tree_100x8.txt deleted +0 -8
1 -
                             ╭────────────────────────────────────────────────────────────────────╮▓
2 -
▿ rustik/                    │ ⊙ a.rs                                                       +2 -1 │▓
3 -
  ⊙ a.rs                     ├────────────────────────────────────────────────────────────────────┤▓
4 -
  ⊙ b.rs                     │ 1    1       context                                               │▓
5 -
                             │ 2          - old                                                   │🮘
6 -
                             │      2     + new                                                   │🮘
7 -
                             │      3     + extra                                                 │🮘
8 -
                             │ 3    4       tail                                                  │🮘