croft-software 0.2.232

VSCode-style TUI written in Rust
//! The multi-root REPOSITORIES overview: one row per workspace folder that is a git
//! repository, drawing them, and the click that picks one.

use super::*;

/// One row of the multi-root REPOSITORIES overview (#161): a workspace
/// folder that is a git repository, as the App's per-folder workers see
/// it each frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RepoRow {
    pub label: String,
    pub branch: Option<String>,
    pub changes: usize,
    pub active: bool,
    pub workspace_root: std::path::PathBuf,
}

impl SourceControlPanel {
    /// Replace the overview's rows; the keys leave REPOSITORIES when it
    /// hides, and its keyboard row stays on the list.
    pub fn set_repositories(&mut self, rows: Vec<RepoRow>) {
        self.repositories = rows;
        self.settle_keys();
    }

    /// How many REPOSITORIES rows the last frame drew. A short panel draws
    /// only the first few, and the keyboard reaches only those, as the mouse
    /// does: a row it cannot see is never the one Enter opens.
    pub(super) fn drawn_repo_rows(&self) -> usize {
        self.repo_row_areas.len().min(self.repositories.len())
    }

    /// REPOSITORIES takes the keys (#871), on the shown repository's row, or
    /// on the last drawn row when that one is below the panel's bottom.
    pub fn focus_repositories(&mut self) {
        self.keys = KeyStop::Repositories;
        let shown = self.repositories.iter().position(|r| r.active).unwrap_or(0);
        self.repo_cursor = shown.min(self.drawn_repo_rows().saturating_sub(1));
    }

    /// Move REPOSITORIES' keyboard row `delta` rows, stopping at the first
    /// and at the last drawn.
    pub fn move_repo_cursor(&mut self, delta: isize) {
        let last = self.drawn_repo_rows().saturating_sub(1);
        self.repo_cursor = self.repo_cursor.saturating_add_signed(delta).min(last);
    }

    /// The repository on REPOSITORIES' keyboard row, if that row was drawn.
    pub fn repo_under_cursor(&self) -> Option<&RepoRow> {
        (self.repo_cursor < self.drawn_repo_rows())
            .then(|| self.repositories.get(self.repo_cursor))
            .flatten()
    }

    /// Paint the multi-root REPOSITORIES overview (#161) starting at `y`,
    /// returning the y below it (unchanged when hidden). One row per
    /// repository: label, branch (dim), change count (right-aligned), the
    /// shown repository's label in bold. The selection background sits on
    /// the shown repository's row, or on the keyboard's row while
    /// REPOSITORIES has the keys (#871), and wears the focus colour only
    /// then, as the change list's does.
    pub(super) fn render_repositories_section(
        &mut self,
        cx: &ViewCx,
        inner: Rect,
        y: u16,
        buf: &mut Buffer,
    ) -> u16 {
        if self.repositories.len() < 2 {
            return y;
        }
        let bottom = inner.y + inner.height;
        let mut y = y;
        if y >= bottom {
            return y;
        }
        let tones = crate::theme::tones(cx.theme);
        buf.set_stringn(
            inner.x + 1,
            y,
            "REPOSITORIES",
            inner.width.saturating_sub(1) as usize,
            Style::default()
                .fg(tones.map_or_else(|| cx.theme.ui(Color::Rgb(0x8a, 0x92, 0xa4)), |t| t.muted()))
                .add_modifier(Modifier::BOLD),
        );
        y += 1;
        let has_keys = self.keys == KeyStop::Repositories;
        for (i, row) in self.repositories.iter().enumerate() {
            if y >= bottom {
                break;
            }
            let picked = if has_keys {
                i == self.repo_cursor
            } else {
                row.active
            };
            let rect = Rect {
                x: inner.x,
                y,
                width: inner.width,
                height: 1,
            };
            // Croft Loch: rows stay on the chrome (the default background
            // painted black bars across it), the active repository wears the
            // selected-row band and bar, the label is body text and the
            // branch muted.
            if let Some(t) = tones {
                let hovered = crate::widgets::hover::contains(rect, cx.pointer);
                // Clear the row onto the chrome first: in the no-repo state
                // the overview paints over the empty-state card's top.
                for x in rect.left()..rect.right() {
                    buf[(x, y)]
                        .set_symbol(" ")
                        .set_style(Style::default().bg(t.chrome()));
                }
                if picked {
                    crate::widgets::surface::paint_selected_row(
                        buf,
                        Rect {
                            x: rect.x.saturating_sub(1),
                            width: rect.width + u16::from(rect.x > 0),
                            ..rect
                        },
                        t,
                        t.chrome,
                        cx.focused && has_keys,
                    );
                } else if hovered {
                    buf.set_style(rect, Style::default().bg(t.hover_on(t.chrome)));
                }
                let branch = row.branch.as_deref().unwrap_or("—");
                let weight = if row.active {
                    Modifier::BOLD
                } else {
                    Modifier::empty()
                };
                let line = Line::from(vec![
                    Span::styled(
                        format!(" {}", row.label),
                        Style::default().fg(t.text()).add_modifier(weight),
                    ),
                    Span::styled(format!("  {branch}"), Style::default().fg(t.muted())),
                ]);
                buf.set_line(rect.x, y, &line, rect.width);
                let left_w = line.width() as u16;
                if row.changes > 0 {
                    let count = row.changes.to_string();
                    let count_x = (rect.x + rect.width).saturating_sub(count.len() as u16 + 1);
                    if count_x > rect.x + left_w {
                        buf.set_string(
                            count_x,
                            y,
                            &count,
                            Style::default().fg(cx.theme.ui(Color::Rgb(0xe0, 0x9a, 0x4e))),
                        );
                    }
                }
                self.repo_row_areas.push((rect, row.workspace_root.clone()));
                y += 1;
                continue;
            }
            let hover_bg = crate::widgets::hover::row_hover_bg(rect, cx.pointer, cx.theme);
            let (bg, fg) = if picked {
                (cx.theme.selection(), cx.theme.ui(Color::White))
            } else if let Some(h) = hover_bg {
                (h, cx.theme.ui(Color::Gray))
            } else {
                (Color::Reset, cx.theme.ui(Color::Gray))
            };
            for x in rect.x..rect.x + rect.width {
                buf[(x, y)].set_bg(bg);
            }
            let branch = row.branch.as_deref().unwrap_or("—");
            let left = format!(" {}  {branch}", row.label);
            buf.set_stringn(
                rect.x,
                y,
                &left,
                rect.width as usize,
                Style::default().bg(bg).fg(fg).add_modifier(if row.active {
                    Modifier::BOLD
                } else {
                    Modifier::empty()
                }),
            );
            if row.changes > 0 {
                let count = row.changes.to_string();
                let count_x = (rect.x + rect.width).saturating_sub(count.len() as u16 + 1);
                if count_x > rect.x + left.len() as u16 {
                    buf.set_string(
                        count_x,
                        y,
                        &count,
                        Style::default()
                            .bg(bg)
                            .fg(cx.theme.ui(Color::Rgb(0xe0, 0x9a, 0x4e))),
                    );
                }
            }
            self.repo_row_areas.push((rect, row.workspace_root.clone()));
            y += 1;
        }
        // One blank spacer so the branch row does not crowd the section.
        y = (y + 1).min(bottom);
        y
    }

    /// Map a click to the repositories-overview row it landed on (#161).
    pub fn click_repository(&self, x: u16, y: u16) -> Option<std::path::PathBuf> {
        self.repo_row_areas
            .iter()
            .find(|(r, _)| x >= r.x && x < r.x + r.width && y == r.y)
            .map(|(_, root)| root.clone())
    }
}