use crate::git::{ChangeEntry, ChangeKind, ChangeSection, GitStatus};
use crate::icons;
use crate::widgets::scrollbar;
use ratatui::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, BorderType, Borders, Paragraph, Widget, Wrap},
};
use std::collections::BTreeSet;
const INPUT_PROMPT_RGB: (u8, u8, u8) = (0x6c, 0x7d, 0x9c);
const BUTTON_BG_RGB: (u8, u8, u8) = (0x09, 0x67, 0xb8);
const BUTTON_FG_RGB: (u8, u8, u8) = (0xff, 0xff, 0xff);
const SECTION_HEADER_RGB: (u8, u8, u8) = (0xcc, 0xcc, 0xcc);
const ADDITIONS_RGB: (u8, u8, u8) = (0xa3, 0xbe, 0x8c);
const DELETIONS_RGB: (u8, u8, u8) = (0xe7, 0x70, 0x70);
pub const DISCARD_GLYPH: char = '\u{21b6}';
pub const STAGE_GLYPH: char = '+';
pub const UNSTAGE_GLYPH: char = '\u{2212}';
const ROW_ACTIONS_WIDTH: u16 = 4;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RowActionAreas {
pub entry_idx: usize,
pub discard: Rect,
pub stage: Rect,
pub unstage: Rect,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommitMenuItem {
CommitAndPush,
Push,
Pull,
Sync,
CheckoutBranch,
Stash,
StashPop,
ViewStagedDiff,
ViewPreviousCommitDiff,
ViewDefaultBranchDiff,
}
impl CommitMenuItem {
pub const ALL: [CommitMenuItem; 10] = [
CommitMenuItem::CommitAndPush,
CommitMenuItem::Push,
CommitMenuItem::Pull,
CommitMenuItem::Sync,
CommitMenuItem::CheckoutBranch,
CommitMenuItem::Stash,
CommitMenuItem::StashPop,
CommitMenuItem::ViewStagedDiff,
CommitMenuItem::ViewPreviousCommitDiff,
CommitMenuItem::ViewDefaultBranchDiff,
];
pub fn label(&self, default_branch: &str) -> String {
match self {
CommitMenuItem::CommitAndPush => "Commit & Push".to_string(),
CommitMenuItem::Push => "Push".to_string(),
CommitMenuItem::Pull => "Pull".to_string(),
CommitMenuItem::Sync => "Sync (Pull, Push)".to_string(),
CommitMenuItem::CheckoutBranch => "Checkout / Create Branch".to_string(),
CommitMenuItem::Stash => "Stash".to_string(),
CommitMenuItem::StashPop => "Pop Stash".to_string(),
CommitMenuItem::ViewStagedDiff => "View Staged Changes".to_string(),
CommitMenuItem::ViewPreviousCommitDiff => "View Changes vs previous".to_string(),
CommitMenuItem::ViewDefaultBranchDiff => {
format!("View Changes vs {default_branch}")
}
}
}
pub fn icon(&self) -> char {
match self {
CommitMenuItem::CommitAndPush => '\u{eac3}',
CommitMenuItem::Push => '\u{eaa1}',
CommitMenuItem::Pull => '\u{eac2}',
CommitMenuItem::Sync => '\u{ea77}',
CommitMenuItem::CheckoutBranch => '\u{ea96}',
CommitMenuItem::Stash => '\u{ea98}',
CommitMenuItem::StashPop => '\u{ea98}',
CommitMenuItem::ViewStagedDiff => '\u{eae1}',
CommitMenuItem::ViewPreviousCommitDiff => '\u{eafd}',
CommitMenuItem::ViewDefaultBranchDiff => '\u{eafd}',
}
}
}
#[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,
}
pub const MESSAGE_MAX_ROWS: usize = 6;
const MESSAGE_LIST_MIN_ROWS: u16 = 2;
pub struct SourceControlPanel {
pub focused: bool,
pub focus_gradient: bool,
pub theme: crate::theme::Theme,
pub message: String,
pub message_cursor: usize,
pub message_scroll: usize,
pub message_line_scroll: usize,
pub status: GitStatus,
seeded_message: Option<String>,
pub entries: Vec<ChangeEntry>,
pub repositories: Vec<RepoRow>,
pub repo_row_areas: Vec<(Rect, std::path::PathBuf)>,
pub last_area: Rect,
pub last_inner: Rect,
pub last_input_area: Rect,
pub last_button_area: Rect,
pub last_commit_caret_area: Rect,
pub commit_menu_item_areas: Vec<(Rect, CommitMenuItem)>,
pub last_list_area: Rect,
pub last_scrollbar: Rect,
pub last_init_repo_button_area: Rect,
pub nested_repos: Vec<(String, std::path::PathBuf)>,
pub nested_repo_button_areas: Vec<(Rect, std::path::PathBuf)>,
pub last_hero_area: Rect,
pub inline_hero_image_active: bool,
pub scroll: usize,
pub selected_change: Option<usize>,
pub multi_selection: BTreeSet<usize>,
pub list_focused: bool,
pub commit_feedback: Option<String>,
pub commit_feedback_is_error: bool,
pub last_row_actions: Option<RowActionAreas>,
pub hover_pointer: Option<(u16, u16)>,
pub header_refresh_btn: Rect,
pub last_branch_area: Rect,
pub header_more_btn: Rect,
}
impl SourceControlPanel {
pub fn new() -> Self {
Self {
focused: false,
focus_gradient: false,
theme: crate::theme::Theme::default(),
message: String::new(),
message_cursor: 0,
message_scroll: 0,
message_line_scroll: 0,
status: GitStatus::default(),
seeded_message: None,
entries: Vec::new(),
repositories: Vec::new(),
repo_row_areas: Vec::new(),
last_area: Rect::default(),
last_inner: Rect::default(),
last_input_area: Rect::default(),
last_button_area: Rect::default(),
last_commit_caret_area: Rect::default(),
commit_menu_item_areas: Vec::new(),
last_list_area: Rect::default(),
last_scrollbar: Rect::default(),
last_init_repo_button_area: Rect::default(),
nested_repos: Vec::new(),
nested_repo_button_areas: Vec::new(),
last_hero_area: Rect::default(),
inline_hero_image_active: false,
scroll: 0,
selected_change: None,
multi_selection: BTreeSet::new(),
list_focused: false,
commit_feedback: None,
commit_feedback_is_error: false,
last_row_actions: None,
hover_pointer: None,
header_refresh_btn: Rect::default(),
last_branch_area: Rect::default(),
header_more_btn: Rect::default(),
}
}
pub fn click_more(&self, x: u16, y: u16) -> bool {
rect_hit(self.header_more_btn, x, y)
}
pub fn click_discard_action(&self, x: u16, y: u16) -> Option<usize> {
let a = self.last_row_actions?;
rect_hit(a.discard, x, y).then_some(a.entry_idx)
}
pub fn click_stage_action(&self, x: u16, y: u16) -> Option<usize> {
let a = self.last_row_actions?;
rect_hit(a.stage, x, y).then_some(a.entry_idx)
}
pub fn click_unstage_action(&self, x: u16, y: u16) -> Option<usize> {
let a = self.last_row_actions?;
rect_hit(a.unstage, x, y).then_some(a.entry_idx)
}
pub fn click_branch(&self, x: u16, y: u16) -> bool {
rect_hit(self.last_branch_area, x, y)
}
pub fn click_header_refresh(&self, x: u16, y: u16) -> bool {
rect_hit(self.header_refresh_btn, x, y)
}
pub fn set_status(&mut self, status: GitStatus, entries: Vec<ChangeEntry>) {
self.status = status;
self.seed_prepared_message();
let row_of = |i: usize| {
self.entries
.get(i)
.map(|e| (e.path.clone(), e.kind.section()))
};
let selected = self.selected_change.and_then(row_of);
let multi: Vec<_> = self
.multi_selection
.iter()
.filter_map(|&i| row_of(i))
.collect();
self.entries = entries;
let rows = &self.entries;
let follow = |(path, section): &(String, crate::git::ChangeSection)| {
let same_row = |e: &ChangeEntry| &e.path == path && e.kind.section() == *section;
rows.iter()
.position(same_row)
.or_else(|| rows.iter().position(|e| &e.path == path))
};
let multi_selection = multi.iter().filter_map(follow).collect();
if let Some(idx) = selected.as_ref().and_then(follow) {
self.selected_change = Some(idx);
} else if let Some(idx) = self.selected_change
&& idx >= self.entries.len()
{
self.selected_change = None;
}
self.multi_selection = multi_selection;
if self.entries.is_empty() {
self.list_focused = false;
}
}
pub fn select_change_at(&mut self, y: u16) -> Option<usize> {
let idx = self.entry_at_y(y)?;
self.selected_change = Some(idx);
self.multi_selection.clear();
self.multi_selection.insert(idx);
Some(idx)
}
pub fn select_all_changes(&mut self) -> usize {
self.multi_selection = (0..self.entries.len()).collect();
if self.selected_change.is_none() && !self.entries.is_empty() {
self.selected_change = Some(0);
}
self.multi_selection.len()
}
pub fn changes_count(&self) -> usize {
self.entries.len()
}
pub fn focus_list(&mut self) -> bool {
let Some(&first) = self.entry_order().first() else {
return false;
};
self.list_focused = true;
if self.selected_change.is_none() {
self.select_only(first);
}
self.reveal_selected();
true
}
pub fn move_selection(&mut self, up: bool) -> bool {
let order = self.entry_order();
let pos = self
.selected_change
.and_then(|s| order.iter().position(|&i| i == s));
let next = match pos {
None => order.first(),
Some(0) if up => return false,
Some(p) if up => order.get(p - 1),
Some(p) => order.get(p + 1),
};
if let Some(&idx) = next {
self.select_only(idx);
self.reveal_selected();
}
true
}
fn entry_order(&self) -> Vec<usize> {
self.list_layout()
.into_iter()
.filter_map(|line| match line {
ListLine::Entry(i) => Some(i),
ListLine::Header(_) => None,
})
.collect()
}
fn select_only(&mut self, idx: usize) {
self.selected_change = Some(idx);
self.multi_selection.clear();
self.multi_selection.insert(idx);
}
fn reveal_selected(&mut self) {
let viewport = self.last_list_area.height as usize;
let lines = self.list_layout();
let Some(line) = self
.selected_change
.and_then(|s| lines.iter().position(|l| *l == ListLine::Entry(s)))
else {
return;
};
if viewport == 0 {
return;
}
let top = match line.checked_sub(1).map(|l| lines[l]) {
Some(ListLine::Header(_)) => line - 1,
_ => line,
};
if top < self.scroll {
self.scroll = top;
} else if line >= self.scroll + viewport {
self.scroll = line + 1 - viewport;
}
}
pub fn insert_char(&mut self, c: char) {
let c = if c == '\r' { '\n' } else { c };
let idx = self.byte_index_at_cursor();
self.message.insert(idx, c);
self.message_cursor += 1;
}
pub fn insert_str(&mut self, s: &str) {
for c in s.replace("\r\n", "\n").chars() {
self.insert_char(c);
}
}
fn caret_line_col(&self) -> (usize, usize) {
let before = self.message.chars().take(self.message_cursor);
let (mut line, mut col) = (0, 0);
for c in before {
if c == '\n' {
line += 1;
col = 0;
} else {
col += 1;
}
}
(line, col)
}
fn set_caret_line_col(&mut self, line: usize, col: usize) {
let mut offset = 0;
for (n, text) in self.message.split('\n').enumerate() {
let len = text.chars().count();
if n == line {
self.message_cursor = offset + col.min(len);
return;
}
offset += len + 1;
}
}
pub fn move_cursor_up(&mut self) -> bool {
let (line, col) = self.caret_line_col();
if line == 0 {
return false;
}
self.set_caret_line_col(line - 1, col);
true
}
pub fn move_cursor_down(&mut self) -> bool {
let (line, col) = self.caret_line_col();
if line + 1 >= self.message.split('\n').count() {
return false;
}
self.set_caret_line_col(line + 1, col);
true
}
pub fn backspace(&mut self) {
if self.message_cursor == 0 {
return;
}
let target = self.message_cursor - 1;
let mut iter = self.message.char_indices();
let mut prev_byte = 0;
for (n, (b, _)) in iter.by_ref().enumerate() {
if n == target {
prev_byte = b;
break;
}
}
let next_byte = iter
.next()
.map(|(b, _)| b)
.unwrap_or_else(|| self.message.len());
self.message.replace_range(prev_byte..next_byte, "");
self.message_cursor = target;
}
pub fn delete_char(&mut self) {
if self.message_cursor >= self.message.chars().count() {
return;
}
let at = self.byte_index_at_cursor();
let next = self.message[at..]
.char_indices()
.nth(1)
.map(|(b, _)| at + b)
.unwrap_or_else(|| self.message.len());
self.message.replace_range(at..next, "");
}
pub fn move_cursor_left(&mut self) {
if self.message_cursor > 0 {
self.message_cursor -= 1;
}
}
pub fn move_cursor_right(&mut self) {
if self.message_cursor < self.message.chars().count() {
self.message_cursor += 1;
}
}
pub fn home(&mut self) {
let (line, _) = self.caret_line_col();
self.set_caret_line_col(line, 0);
}
pub fn end(&mut self) {
let (line, _) = self.caret_line_col();
self.set_caret_line_col(line, usize::MAX);
}
pub fn message_start(&mut self) {
self.message_cursor = 0;
}
pub fn message_end(&mut self) {
self.message_cursor = self.message.chars().count();
}
pub fn seed_prepared_message(&mut self) {
let prepared = self
.status
.prepared_message
.as_deref()
.map(|m| m.trim().to_string());
match prepared {
Some(prepared) => {
if let Some(seed) = self.seeded_message.as_deref()
&& seed != prepared
&& self.message == seed
{
self.clear_message();
self.seeded_message = None;
}
if self.message.is_empty()
&& !prepared.is_empty()
&& self.seeded_message.as_deref() != Some(prepared.as_str())
{
self.insert_str(&prepared);
self.seeded_message = Some(prepared);
}
}
None => {
if let Some(seed) = self.seeded_message.take()
&& self.message == seed
{
self.clear_message();
}
}
}
}
pub fn clear_after_commit(&mut self) {
self.clear_message();
self.seeded_message = None;
}
pub fn clear_message(&mut self) {
self.message.clear();
self.message_cursor = 0;
self.message_scroll = 0;
self.message_line_scroll = 0;
}
pub fn entry_at_y(&self, y: u16) -> Option<usize> {
if y < self.last_list_area.y || y >= self.last_list_area.y + self.last_list_area.height {
return None;
}
let row = (y - self.last_list_area.y) as usize;
let lines = self.list_layout();
let line_idx = self.scroll + row;
match lines.get(line_idx)? {
ListLine::Entry(idx) => Some(*idx),
ListLine::Header(_) => None,
}
}
pub fn click_button(&self, x: u16, y: u16) -> bool {
rect_hit(self.last_button_area, x, y)
}
pub fn click_commit_caret(&self, x: u16, y: u16) -> bool {
rect_hit(self.last_commit_caret_area, x, y)
}
pub fn click_commit_menu_item(&self, x: u16, y: u16) -> Option<CommitMenuItem> {
self.commit_menu_item_areas
.iter()
.find(|(rect, _)| rect_hit(*rect, x, y))
.map(|(_, item)| *item)
}
pub fn click_input(&self, x: u16, y: u16) -> bool {
let rect = self.last_input_area;
rect.width > 0
&& rect.height > 0
&& x >= rect.x
&& x < rect.x + rect.width
&& y >= rect.y
&& y < rect.y + rect.height
}
pub fn click_init_repo_button(&self, x: u16, y: u16) -> bool {
rect_hit(self.last_init_repo_button_area, x, y)
}
pub fn click_nested_repo(&self, x: u16, y: u16) -> Option<std::path::PathBuf> {
self.nested_repo_button_areas
.iter()
.find(|(r, _)| rect_hit(*r, x, y))
.map(|(_, path)| path.clone())
}
pub fn scroll_up(&mut self, rows: usize) {
self.scroll = self.scroll.saturating_sub(rows);
}
pub fn scroll_down(&mut self, rows: usize) {
let max = self
.list_layout()
.len()
.saturating_sub(self.last_list_area.height as usize);
self.scroll = (self.scroll + rows).min(max);
}
pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
let total = self.list_layout().len();
let viewport = self.last_list_area.height as usize;
let Some(metrics) =
scrollbar::vertical_metrics(self.last_scrollbar, total, viewport, self.scroll)
else {
return false;
};
self.scroll = scrollbar::scroll_for_y(metrics, y);
true
}
fn byte_index_at_cursor(&self) -> usize {
self.message
.char_indices()
.nth(self.message_cursor)
.map(|(b, _)| b)
.unwrap_or_else(|| self.message.len())
}
pub fn cursor_screen_pos(&self) -> Option<(u16, u16)> {
if !self.focused || self.list_focused {
return None;
}
let r = self.last_input_area;
if r.width < 3 || r.height < 3 {
return None;
}
let (line, col) = self.caret_line_col();
let cursor_col = col.saturating_sub(self.message_scroll) as u16;
let max_col = r.width.saturating_sub(3);
if cursor_col > max_col {
return None;
}
let row = line.checked_sub(self.message_line_scroll)? as u16;
if row + 2 >= r.height {
return None;
}
Some((r.x + 2 + cursor_col, r.y + 1 + row))
}
fn list_layout(&self) -> Vec<ListLine> {
let mut out = Vec::new();
for section in [
ChangeSection::Conflicts,
ChangeSection::Staged,
ChangeSection::Changes,
ChangeSection::Untracked,
] {
let mut any = false;
for (i, entry) in self.entries.iter().enumerate() {
if entry.kind.section() == section {
if !any {
out.push(ListLine::Header(section));
any = true;
}
out.push(ListLine::Entry(i));
}
}
}
out
}
fn render_repositories_section(&mut self, 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;
}
buf.set_stringn(
inner.x + 1,
y,
"REPOSITORIES",
inner.width.saturating_sub(1) as usize,
Style::default()
.fg(self.theme.ui(Color::Rgb(0x8a, 0x92, 0xa4)))
.add_modifier(Modifier::BOLD),
);
y += 1;
for row in &self.repositories {
if y >= bottom {
break;
}
let rect = Rect {
x: inner.x,
y,
width: inner.width,
height: 1,
};
let hover_bg =
crate::widgets::hover::row_hover_bg(rect, self.hover_pointer, self.theme);
let (bg, fg) = if row.active {
(self.theme.selection(), self.theme.ui(Color::White))
} else if let Some(h) = hover_bg {
(h, self.theme.ui(Color::Gray))
} else {
(Color::Reset, self.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 cx = (rect.x + rect.width).saturating_sub(count.len() as u16 + 1);
if cx > rect.x + left.len() as u16 {
buf.set_string(
cx,
y,
&count,
Style::default()
.bg(bg)
.fg(self.theme.ui(Color::Rgb(0xe0, 0x9a, 0x4e))),
);
}
}
self.repo_row_areas.push((rect, row.workspace_root.clone()));
y += 1;
}
y = (y + 1).min(bottom);
y
}
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())
}
fn render_no_repo_empty_state(&mut self, inner: Rect, buf: &mut Buffer) {
if inner.height < 4 || inner.width < 8 {
return;
}
let card_top = inner.y + 2;
let card_bottom = inner.y + inner.height - 1;
let card_h = card_bottom.saturating_sub(card_top);
if card_h < 3 {
return;
}
let side_pad: u16 = if inner.width >= 24 { 2 } else { 1 };
let card_x = inner.x + side_pad;
let card_w = inner.width.saturating_sub(side_pad * 2);
let card_area = Rect {
x: card_x,
y: card_top,
width: card_w,
height: card_h,
};
let card_border = Style::default().fg(self.theme.ui(Color::Rgb(0x60, 0x68, 0x78)));
let card_block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(card_border);
let card_inner = card_block.inner(card_area);
card_block.render(card_area, buf);
if card_inner.width < 4 || card_inner.height < 3 {
return;
}
let blue = if self.focus_gradient {
crate::gradient::rgb_color(crate::gradient::CARD_ACCENT)
} else {
self.theme.ui(Color::Rgb(0x60, 0x9a, 0xfe))
};
let dim_blue = self.theme.ui(Color::Rgb(0x4b, 0x50, 0x5a));
let text_white = self.theme.ui(Color::Rgb(0xff, 0xff, 0xff));
let text_dim = self.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4));
let blue_bg = if self.focus_gradient {
crate::gradient::rgb_color(crate::gradient::PRIMARY_BTN_BG)
} else {
Color::Rgb(BUTTON_BG_RGB.0, BUTTON_BG_RGB.1, BUTTON_BG_RGB.2)
};
let mut y = card_inner.y + 2;
let bottom = card_inner.y + card_inner.height;
let hero_h: u16 = if card_inner.height >= 18 {
8
} else if card_inner.height >= 14 {
7
} else {
5
};
let hero_w: u16 = (hero_h * 2).min(card_inner.width).max(7);
let hero_x = card_inner.x + (card_inner.width.saturating_sub(hero_w)) / 2;
if y + hero_h <= bottom {
self.last_hero_area = Rect {
x: hero_x,
y,
width: hero_w,
height: hero_h,
};
if !self.inline_hero_image_active {
if card_inner.width >= 13 && hero_h >= 7 {
paint_y_fork_illustration(buf, card_inner, y, dim_blue, blue);
} else {
paint_y_fork_compact(buf, card_inner, y, blue);
}
}
y += hero_h + 1;
}
let nested = !self.nested_repos.is_empty();
let title_text = if nested {
"Repositories found in subfolders"
} else {
"No repository detected"
};
let title_h = paragraph_line_count(title_text, card_inner.width).min(3) as u16;
if y + title_h <= bottom && title_h > 0 {
let title_rect = Rect {
x: card_inner.x,
y,
width: card_inner.width,
height: title_h,
};
let title = Paragraph::new(title_text)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true })
.style(Style::default().fg(text_white).add_modifier(Modifier::BOLD));
title.render(title_rect, buf);
y += title_h + 1;
}
let desc_text = if nested {
"This folder is not a Git repository, but these subfolders are. Open one to use Source Control."
} else {
"Open a folder under Git or create a new repository to start tracking changes."
};
let desc_h = paragraph_line_count(desc_text, card_inner.width).min(6) as u16;
if y + desc_h <= bottom && desc_h > 0 {
let desc_rect = Rect {
x: card_inner.x,
y,
width: card_inner.width,
height: desc_h,
};
let desc = Paragraph::new(desc_text)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true })
.style(Style::default().fg(text_dim));
desc.render(desc_rect, buf);
y += desc_h + 2;
}
let max_btn_w: u16 = 40;
let btn_w = card_inner.width.saturating_sub(2).min(max_btn_w);
let btn_x = card_inner.x + (card_inner.width.saturating_sub(btn_w)) / 2;
if nested {
for (label, path) in &self.nested_repos {
if y + 3 > bottom || btn_w < 6 {
break;
}
let area = Rect {
x: btn_x,
y,
width: btn_w,
height: 3,
};
let text = format!("Open {label}");
render_rounded_button(buf, area, &text, blue_bg, text_white);
self.nested_repo_button_areas.push((area, path.clone()));
y += 4;
}
return;
}
let init_label: &str = if btn_w >= 23 {
"Initialize Repository"
} else if btn_w >= 12 {
"Initialize"
} else {
"Init"
};
if y + 3 <= bottom && btn_w >= 6 {
let init_area = Rect {
x: btn_x,
y,
width: btn_w,
height: 3,
};
self.last_init_repo_button_area = init_area;
render_rounded_button(buf, init_area, init_label, blue_bg, text_white);
}
}
}
fn paragraph_line_count(text: &str, width: u16) -> usize {
if width == 0 || text.is_empty() {
return 0;
}
let max = width as usize;
let mut lines: usize = 1;
let mut current: usize = 0;
for word in text.split_whitespace() {
let wlen = word.chars().count();
if current == 0 {
current = wlen.min(max);
if wlen > max {
lines += wlen / max;
current = wlen % max;
}
} else if current + 1 + wlen <= max {
current += 1 + wlen;
} else {
lines += 1;
current = wlen.min(max);
if wlen > max {
lines += wlen / max;
current = wlen % max;
}
}
}
lines
}
fn paint_y_fork_illustration(
buf: &mut Buffer,
card_inner: Rect,
top_y: u16,
dim_blue: Color,
blue: Color,
) {
let dot = Style::default().fg(dim_blue);
let trunk = Style::default().fg(blue);
let node = Style::default().fg(blue).add_modifier(Modifier::BOLD);
let cx = card_inner.x + card_inner.width / 2;
let arc = "· · · · ·";
let arc_w = arc.chars().count() as u16;
let arc_x = card_inner.x + (card_inner.width - arc_w) / 2;
buf.set_string(arc_x, top_y, arc, dot);
buf.set_string(arc_x, top_y + 6, arc, dot);
let side_off: u16 = 5;
if cx > card_inner.x + side_off {
buf.set_string(cx - side_off, top_y + 1, "·", dot);
buf.set_string(cx - side_off, top_y + 3, "·", dot);
buf.set_string(cx - side_off, top_y + 5, "·", dot);
}
if cx + side_off < card_inner.x + card_inner.width {
buf.set_string(cx + side_off, top_y + 1, "·", dot);
buf.set_string(cx + side_off, top_y + 3, "·", dot);
buf.set_string(cx + side_off, top_y + 5, "·", dot);
}
buf.set_string(cx, top_y + 1, "●", node);
buf.set_string(cx, top_y + 2, "│", trunk);
buf.set_string(cx, top_y + 3, "●", node);
buf.set_string(cx + 1, top_y + 3, "─", trunk);
if cx + 2 < card_inner.x + card_inner.width {
buf.set_string(cx + 2, top_y + 3, "●", node);
}
buf.set_string(cx, top_y + 4, "│", trunk);
buf.set_string(cx, top_y + 5, "●", node);
}
fn paint_y_fork_compact(buf: &mut Buffer, card_inner: Rect, top_y: u16, blue: Color) {
let trunk = Style::default().fg(blue);
let node = Style::default().fg(blue).add_modifier(Modifier::BOLD);
let cx = card_inner.x + card_inner.width / 2;
buf.set_string(cx, top_y, "●", node);
buf.set_string(cx, top_y + 1, "│", trunk);
buf.set_string(cx, top_y + 2, "●", node);
buf.set_string(cx + 1, top_y + 2, "─", trunk);
if cx + 2 < card_inner.x + card_inner.width {
buf.set_string(cx + 2, top_y + 2, "●", node);
}
buf.set_string(cx, top_y + 3, "│", trunk);
buf.set_string(cx, top_y + 4, "●", node);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ListLine {
Header(ChangeSection),
Entry(usize),
}
impl Default for SourceControlPanel {
fn default() -> Self {
Self::new()
}
}
fn section_label(section: ChangeSection) -> &'static str {
match section {
ChangeSection::Conflicts => "MERGE CONFLICTS",
ChangeSection::Staged => "STAGED CHANGES",
ChangeSection::Changes => "CHANGES",
ChangeSection::Untracked => "UNTRACKED",
}
}
fn rect_hit(rect: Rect, x: u16, y: u16) -> bool {
rect.width > 0
&& rect.height > 0
&& x >= rect.x
&& x < rect.x + rect.width
&& y >= rect.y
&& y < rect.y + rect.height
}
pub fn render_rounded_button(buf: &mut Buffer, area: Rect, label: &str, bg: Color, fg: Color) {
if area.width < 2 || area.height < 1 {
return;
}
let solid = Style::default().bg(bg);
for ry in 0..area.height {
for rx in 0..area.width {
buf[(area.x + rx, area.y + ry)]
.set_symbol(" ")
.set_style(solid);
}
}
let corner_style = Style::default().fg(bg);
if area.height >= 2 {
buf[(area.x, area.y)]
.set_symbol("╭")
.set_style(corner_style);
buf[(area.x + area.width - 1, area.y)]
.set_symbol("╮")
.set_style(corner_style);
buf[(area.x, area.y + area.height - 1)]
.set_symbol("╰")
.set_style(corner_style);
buf[(area.x + area.width - 1, area.y + area.height - 1)]
.set_symbol("╯")
.set_style(corner_style);
}
let max_w = area.width as usize;
let visible_label: String = label.chars().take(max_w).collect();
if visible_label.is_empty() {
return;
}
let label_w = visible_label.chars().count() as u16;
let label_x = area.x + (area.width - label_w) / 2;
let label_y = area.y + area.height / 2;
buf.set_string(
label_x,
label_y,
&visible_label,
Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
);
}
fn badge_color(kind: ChangeKind, theme: crate::theme::Theme) -> Color {
match kind {
ChangeKind::StagedAdded => theme.ui(Color::Rgb(0x81, 0xb8, 0x8c)),
ChangeKind::StagedModified | ChangeKind::Modified => theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b)),
ChangeKind::StagedDeleted | ChangeKind::Deleted => theme.ui(Color::Rgb(0xe7, 0x70, 0x70)),
ChangeKind::StagedRenamed => theme.ui(Color::Rgb(0xb4, 0x8e, 0xad)),
ChangeKind::Untracked => theme.ui(Color::Rgb(0x88, 0xc0, 0xd0)),
ChangeKind::Conflicted => theme.ui(Color::Rgb(0xe7, 0x4c, 0x3c)),
}
}
impl Widget for &mut SourceControlPanel {
fn render(self, area: Rect, buf: &mut Buffer) {
let focus_blue = self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff));
let accent = if self.focus_gradient {
crate::gradient::rgb_color(crate::gradient::INNER_ACCENT)
} else {
focus_blue
};
let outer_style = if self.focused {
Style::default().fg(focus_blue)
} else {
Style::default().fg(Color::DarkGray)
};
let outer = crate::widgets::surface::view_block(self.theme, true, outer_style);
let inner = outer.inner(area);
outer.render(area, buf);
crate::widgets::surface::paint_view_focus(
buf,
area,
self.theme,
self.focused,
self.focus_gradient,
);
self.last_area = area;
self.last_inner = inner;
self.last_input_area = Rect::default();
self.last_button_area = Rect::default();
self.last_commit_caret_area = Rect::default();
self.commit_menu_item_areas.clear();
self.last_list_area = Rect::default();
self.last_scrollbar = Rect::default();
self.last_row_actions = None;
self.header_refresh_btn = Rect::default();
self.last_branch_area = Rect::default();
self.header_more_btn = Rect::default();
self.repo_row_areas.clear();
if inner.height == 0 || inner.width == 0 {
return;
}
let header_title = crate::i18n::tr("SOURCE CONTROL");
let title_end = inner.x
+ u16::try_from(unicode_width::UnicodeWidthStr::width(header_title.as_ref()))
.unwrap_or(u16::MAX)
.saturating_add(1);
buf.set_stringn(
inner.x,
inner.y,
&header_title,
inner.width as usize,
Style::default()
.fg(self.theme.ui(Color::Rgb(0xb0, 0xb8, 0xc8)))
.add_modifier(Modifier::BOLD),
);
let pill_w: u16 = 2;
let refresh_x = (inner.x + inner.width).saturating_sub(pill_w + 1);
if self.status.in_repo && refresh_x > title_end {
let rect = Rect {
x: refresh_x,
y: inner.y,
width: pill_w,
height: 1,
};
self.header_refresh_btn = rect;
let hovered = crate::widgets::hover::contains(rect, self.hover_pointer);
crate::widgets::header_pill::render(
buf,
refresh_x,
inner.y,
crate::widgets::header_pill::REFRESH_GLYPH,
self.theme,
hovered,
);
let more_x = refresh_x.saturating_sub(pill_w + 1);
if more_x > title_end {
let more_rect = Rect {
x: more_x,
y: inner.y,
width: pill_w,
height: 1,
};
self.header_more_btn = more_rect;
let more_hovered = crate::widgets::hover::contains(more_rect, self.hover_pointer);
crate::widgets::header_pill::render(
buf,
more_x,
inner.y,
crate::widgets::scm_menu::ICON_ELLIPSIS,
self.theme,
more_hovered,
);
}
}
if !self.status.in_repo {
self.last_init_repo_button_area = Rect::default();
self.nested_repo_button_areas.clear();
self.last_hero_area = Rect::default();
self.render_no_repo_empty_state(inner, buf);
self.render_repositories_section(inner, inner.y + 2, buf);
return;
}
self.last_hero_area = Rect::default();
self.nested_repo_button_areas.clear();
let mut y = inner.y + 2;
y = self.render_repositories_section(inner, y, buf);
if y >= inner.y + inner.height {
return;
}
let mut spans: Vec<Span> = Vec::with_capacity(5);
spans.push(Span::styled(
"\u{ea68} ",
Style::default().fg(self.theme.ui(Color::Rgb(0x88, 0xc0, 0xd0))),
));
let label = self.status.head_label().to_string();
let branch_w = (2 + label.chars().count() as u16).min(inner.width);
self.last_branch_area = Rect {
x: inner.x,
y,
width: branch_w,
height: 1,
};
spans.push(Span::styled(
label,
Style::default()
.fg(self.theme.ui(Color::White))
.add_modifier(Modifier::BOLD),
));
if let Some(op) = self.status.operation {
spans.push(Span::styled(
format!(" {}", op.label()),
Style::default()
.fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b)))
.add_modifier(Modifier::BOLD),
));
}
if self.status.ahead > 0 {
spans.push(Span::styled(
format!(" \u{2191}{}", self.status.ahead),
Style::default().fg(self.theme.ui(Color::Rgb(0xa3, 0xbe, 0x8c))),
));
}
if self.status.behind > 0 {
spans.push(Span::styled(
format!(" \u{2193}{}", self.status.behind),
Style::default().fg(self.theme.ui(Color::Rgb(0xeb, 0xcb, 0x8b))),
));
}
buf.set_line(inner.x, y, &Line::from(spans), inner.width);
y += 2;
if y + 3 > inner.y + inner.height {
return;
}
let line_count = self.message.split('\n').count();
let feedback_rows = if self.commit_feedback.is_some() { 2 } else { 0 };
let below = 1 + 3 + 1 + feedback_rows + 1 + MESSAGE_LIST_MIN_ROWS;
let left = inner.y + inner.height - y;
let input_box = Rect {
x: inner.x,
y,
width: inner.width,
height: (line_count.clamp(1, MESSAGE_MAX_ROWS) as u16 + 2)
.min(left.saturating_sub(below).max(3))
.min(left),
};
self.last_input_area = input_box;
let input_border_style = if self.focused && !self.list_focused {
Style::default().fg(accent)
} else {
Style::default().fg(self.theme.ui(Color::Rgb(0x60, 0x68, 0x78)))
};
let input_block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(input_border_style);
let input_inner = input_block.inner(input_box);
input_block.render(input_box, buf);
if input_inner.width > 0 && input_inner.height > 0 {
let content_y = input_inner.y;
let text_x = input_inner.x + 1;
let text_max = (input_inner.width as usize).saturating_sub(2);
if self.message.is_empty() {
self.message_scroll = 0;
self.message_line_scroll = 0;
buf.set_stringn(
text_x,
content_y,
"Message (Enter = commit, \u{21e7}Enter = new line, \u{2303}Enter = push)",
text_max,
Style::default()
.fg(Color::Rgb(
INPUT_PROMPT_RGB.0,
INPUT_PROMPT_RGB.1,
INPUT_PROMPT_RGB.2,
))
.add_modifier(Modifier::ITALIC),
);
} else {
let (line, cursor) = self.caret_line_col();
if cursor < self.message_scroll {
self.message_scroll = cursor;
} else if text_max > 0 && cursor > self.message_scroll + text_max {
self.message_scroll = cursor - text_max;
}
let rows = input_inner.height as usize;
if line < self.message_line_scroll {
self.message_line_scroll = line;
} else if line >= self.message_line_scroll + rows {
self.message_line_scroll = line + 1 - rows;
}
for (row, text) in self
.message
.split('\n')
.skip(self.message_line_scroll)
.take(rows)
.enumerate()
{
let visible: String = text
.chars()
.skip(self.message_scroll)
.take(text_max)
.collect();
buf.set_stringn(
text_x,
content_y + row as u16,
&visible,
text_max,
Style::default().fg(self.theme.ui(Color::White)),
);
}
}
}
y += input_box.height + 1;
if y + 3 > inner.y + inner.height {
return;
}
let blue = if self.focus_gradient {
crate::gradient::rgb_color(crate::gradient::PRIMARY_BTN_BG)
} else {
Color::Rgb(BUTTON_BG_RGB.0, BUTTON_BG_RGB.1, BUTTON_BG_RGB.2)
};
let white = Color::Rgb(BUTTON_FG_RGB.0, BUTTON_FG_RGB.1, BUTTON_FG_RGB.2);
let split_caret_w: u16 = 3;
let split_gap_w: u16 = 1;
if inner.width >= 16 + split_caret_w + split_gap_w {
let main_w = inner.width.saturating_sub(split_caret_w + split_gap_w);
let main_area = Rect {
x: inner.x,
y,
width: main_w,
height: 3,
};
let caret_area = Rect {
x: inner.x + main_w + split_gap_w,
y,
width: split_caret_w,
height: 3,
};
self.last_button_area = main_area;
self.last_commit_caret_area = caret_area;
render_rounded_button(buf, main_area, "\u{eab2} Commit", blue, white);
render_rounded_button(buf, caret_area, "▾", blue, white);
} else {
let button_area = Rect {
x: inner.x,
y,
width: inner.width,
height: 3,
};
self.last_button_area = button_area;
render_rounded_button(buf, button_area, "Commit", blue, white);
}
y += 3 + 1;
if let Some(msg) = self.commit_feedback.as_ref()
&& y < inner.y + inner.height
{
let style = if self.commit_feedback_is_error {
Style::default().fg(self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)))
} else {
Style::default().fg(self.theme.ui(Color::Rgb(0xa3, 0xbe, 0x8c)))
};
let line = crate::git::headline(msg);
let rows = wrap_feedback(line, inner.width as usize, FEEDBACK_MAX_ROWS);
for row in &rows {
if y >= inner.y + inner.height {
break;
}
buf.set_stringn(inner.x, y, row, inner.width as usize, style);
y += 1;
}
y += 1;
}
if y >= inner.y + inner.height {
return;
}
let sep_style = Style::default().fg(self.theme.ui(Color::Rgb(0x40, 0x48, 0x58)));
for x in inner.x..inner.x + inner.width {
buf.set_string(x, y, "─", sep_style);
}
y += 1;
if y >= inner.y + inner.height {
return;
}
let list_area = Rect {
x: inner.x,
y,
width: inner.width,
height: inner.y + inner.height - y,
};
self.last_list_area = list_area;
let lines = self.list_layout();
let total = lines.len();
let viewport = list_area.height as usize;
if viewport == 0 {
return;
}
if self.scroll > total.saturating_sub(viewport) {
self.scroll = total.saturating_sub(viewport);
}
let scrollbar_area = Rect {
x: list_area.x + list_area.width.saturating_sub(1),
y: list_area.y,
width: u16::from(list_area.width > 0),
height: list_area.height,
};
let scrollbar_metrics =
scrollbar::vertical_metrics(scrollbar_area, total, viewport, self.scroll);
if let Some(m) = scrollbar_metrics {
self.last_scrollbar = m.area;
}
let row_width = list_area
.width
.saturating_sub(u16::from(scrollbar_metrics.is_some()));
if total == 0 {
buf.set_stringn(
list_area.x,
list_area.y,
"No changes",
list_area.width as usize,
Style::default().fg(Color::DarkGray),
);
return;
}
let selected_bg = self.theme.ui(Color::Rgb(0x26, 0x4f, 0x78));
let end = (self.scroll + viewport).min(total);
for (row, idx) in (self.scroll..end).enumerate() {
let row_y = list_area.y + row as u16;
match &lines[idx] {
ListLine::Header(section) => {
let (count, sec_add, sec_del) = self
.entries
.iter()
.filter(|e| e.kind.section() == *section)
.fold((0usize, 0usize, 0usize), |(c, a, d), e| {
(c + 1, a + e.additions, d + e.deletions)
});
let mut header_spans = vec![
Span::styled(
"\u{25be} ",
Style::default().fg(self.theme.ui(Color::Rgb(0xb0, 0xb8, 0xc8))),
),
Span::styled(
section_label(*section),
Style::default()
.fg(Color::Rgb(
SECTION_HEADER_RGB.0,
SECTION_HEADER_RGB.1,
SECTION_HEADER_RGB.2,
))
.add_modifier(Modifier::BOLD),
),
Span::raw(" "),
Span::styled(
format!(" {count} "),
Style::default()
.fg(self.theme.ui(Color::White))
.bg(self.theme.ui(Color::Rgb(0x2a, 0x33, 0x42)))
.add_modifier(Modifier::BOLD),
),
];
if sec_add > 0 || sec_del > 0 {
header_spans.push(Span::raw(" "));
if sec_add > 0 {
header_spans.push(Span::styled(
format!("+{sec_add}"),
Style::default()
.fg(Color::Rgb(
ADDITIONS_RGB.0,
ADDITIONS_RGB.1,
ADDITIONS_RGB.2,
))
.add_modifier(Modifier::BOLD),
));
}
if sec_add > 0 && sec_del > 0 {
header_spans.push(Span::raw(" "));
}
if sec_del > 0 {
header_spans.push(Span::styled(
format!("-{sec_del}"),
Style::default()
.fg(Color::Rgb(
DELETIONS_RGB.0,
DELETIONS_RGB.1,
DELETIONS_RGB.2,
))
.add_modifier(Modifier::BOLD),
));
}
}
buf.set_line(list_area.x, row_y, &Line::from(header_spans), row_width);
}
ListLine::Entry(entry_idx) => {
let entry = &self.entries[*entry_idx];
let row_rect = Rect {
x: list_area.x,
y: row_y,
width: row_width,
height: 1,
};
let is_primary = self.selected_change == Some(*entry_idx);
let is_in_multi = self.multi_selection.contains(entry_idx);
let row_bg = if is_primary {
Some(selected_bg)
} else if is_in_multi {
Some(self.theme.ui(Color::Rgb(0x1f, 0x3a, 0x5c)))
} else {
crate::widgets::hover::row_hover_bg(
row_rect,
self.hover_pointer,
self.theme,
)
};
let is_selected = is_primary;
if let Some(bg) = row_bg {
let row_bg_style = Style::default().bg(bg);
for rx in 0..row_rect.width {
buf[(row_rect.x + rx, row_rect.y)]
.set_symbol(" ")
.set_style(row_bg_style);
}
}
let path_str = entry.path.as_str();
let is_dir = path_str.ends_with('/');
let icon = if is_dir {
icons::FOLDER_CLOSED
} else {
let basename = std::path::Path::new(path_str)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| path_str.to_string());
let suffix = std::path::Path::new(&basename)
.extension()
.map(|e| format!(".{}", e.to_string_lossy()))
.unwrap_or_default();
icons::for_path(&basename, &suffix)
};
let badge = entry.kind.badge();
let badge_str = badge.to_string();
let badge_w: u16 = 1;
let row_padding: u16 = 1;
let badge_x = row_rect
.x
.saturating_add(row_rect.width.saturating_sub(badge_w + row_padding));
let mut badge_style = Style::default()
.fg(badge_color(entry.kind, self.theme))
.add_modifier(Modifier::BOLD);
let mut icon_style = Style::default().fg(self.theme.ui(icon.color));
let mut path_style = Style::default().fg(self.theme.ui(Color::White));
if let Some(bg) = row_bg {
badge_style = badge_style.bg(bg);
icon_style = icon_style.bg(bg);
path_style = path_style.bg(bg);
}
if row_rect.width > badge_w + row_padding + 4 {
buf.set_string(badge_x, row_y, badge_str.as_str(), badge_style);
}
let icon_x = row_rect.x + 1;
buf.set_string(icon_x, row_y, icon.glyph.to_string(), icon_style);
let text_x = icon_x + 2;
let is_staged = entry.kind.section() == ChangeSection::Staged;
let text_w_unreserved = badge_x.saturating_sub(text_x).saturating_sub(1);
let show_actions = is_selected && text_w_unreserved > ROW_ACTIONS_WIDTH;
let text_w_reserved = if show_actions { ROW_ACTIONS_WIDTH } else { 0 };
let text_w = text_w_unreserved.saturating_sub(text_w_reserved);
if text_w > 0 {
let path_para = Paragraph::new(path_str).style(path_style);
path_para.render(
Rect {
x: text_x,
y: row_y,
width: text_w,
height: 1,
},
buf,
);
}
if show_actions {
let action_fg = self.theme.ui(Color::Rgb(0xd4, 0xd9, 0xe2));
let mut action_style = Style::default().fg(action_fg);
if let Some(bg) = row_bg {
action_style = action_style.bg(bg);
}
let cell = |x: u16| Rect {
x,
y: row_y,
width: 1,
height: 1,
};
if is_staged {
let unstage_x = badge_x - 2;
buf.set_string(
unstage_x,
row_y,
UNSTAGE_GLYPH.to_string(),
action_style,
);
self.last_row_actions = Some(RowActionAreas {
entry_idx: *entry_idx,
discard: Rect::default(),
stage: Rect::default(),
unstage: cell(unstage_x),
});
} else {
let discard_x = badge_x - 4;
let stage_x = badge_x - 2;
buf.set_string(
discard_x,
row_y,
DISCARD_GLYPH.to_string(),
action_style,
);
buf.set_string(stage_x, row_y, STAGE_GLYPH.to_string(), action_style);
self.last_row_actions = Some(RowActionAreas {
entry_idx: *entry_idx,
discard: cell(discard_x),
stage: cell(stage_x),
unstage: Rect::default(),
});
}
}
}
}
}
if let Some(metrics) = scrollbar_metrics {
scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
}
}
}
const FEEDBACK_MAX_ROWS: usize = 4;
fn wrap_feedback(msg: &str, width: usize, max_rows: usize) -> Vec<String> {
use unicode_width::UnicodeWidthStr as _;
if width == 0 {
return Vec::new();
}
let mut rows: Vec<String> = Vec::new();
let mut row = String::new();
for word in msg.split_whitespace() {
let gap = usize::from(!row.is_empty());
if row.width() + gap + word.width() <= width {
if gap == 1 {
row.push(' ');
}
row.push_str(word);
continue;
}
if !row.is_empty() {
rows.push(std::mem::take(&mut row));
}
for c in word.chars() {
if row.width() + unicode_width::UnicodeWidthChar::width(c).unwrap_or(0) > width {
rows.push(std::mem::take(&mut row));
}
row.push(c);
}
}
if !row.is_empty() {
rows.push(row);
}
if rows.len() > max_rows {
rows.truncate(max_rows);
let last = &mut rows[max_rows - 1];
while last.width() + 1 > width {
last.pop();
}
last.push('…');
}
rows
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_char_appends_and_moves_cursor() {
let mut p = SourceControlPanel::new();
p.insert_char('h');
p.insert_char('i');
assert_eq!(p.message, "hi");
assert_eq!(p.message_cursor, 2);
}
#[test]
fn backspace_deletes_previous_char() {
let mut p = SourceControlPanel::new();
p.insert_str("abc");
p.backspace();
assert_eq!(p.message, "ab");
assert_eq!(p.message_cursor, 2);
}
#[test]
fn backspace_at_start_is_noop() {
let mut p = SourceControlPanel::new();
p.backspace();
assert_eq!(p.message, "");
assert_eq!(p.message_cursor, 0);
}
#[test]
fn hovering_an_unselected_change_row_lifts_it() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.focus_gradient = false; p.theme = crate::theme::Theme::DARK_BLUE;
p.status.in_repo = true;
p.selected_change = None; p.entries = vec![
ChangeEntry {
path: "a.rs".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b.rs".into(),
kind: ChangeKind::Modified,
..Default::default()
},
];
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 24,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let row_y = p.last_list_area.y + 2;
p.hover_pointer = Some((p.last_list_area.x, row_y));
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert_eq!(
buf[(p.last_list_area.x, row_y)].bg,
Color::Rgb(0x2b, 0x31, 0x42),
"the hovered unselected change row wears the Croft Dark hover lift"
);
}
#[test]
fn header_refresh_pill_renders_in_repo_and_hit_tests() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.status.in_repo = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 24,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let btn = p.header_refresh_btn;
assert!(btn.width > 0, "the refresh pill must render inside a repo");
let header_row: String = (0..area.width)
.map(|x| buf[(x, btn.y)].symbol().chars().next().unwrap_or(' '))
.collect();
assert!(
header_row.contains(crate::widgets::header_pill::REFRESH_GLYPH),
"header row must paint the cod-refresh glyph (got: {header_row:?})",
);
assert!(p.click_header_refresh(btn.x, btn.y));
assert!(!p.click_header_refresh(btn.x.saturating_sub(2), btn.y));
}
#[test]
fn long_commit_feedback_wraps_inside_the_panel() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.status.in_repo = true;
let msg = "Resolve 1 merge conflict (README.md) and stage it before committing";
p.commit_feedback = Some(String::from(msg));
p.commit_feedback_is_error = true;
let area = Rect {
x: 0,
y: 0,
width: 32,
height: 30,
};
let mut buf = Buffer::empty(Rect { width: 80, ..area });
(&mut p).render(area, &mut buf);
let row = |y: u16, xs: std::ops::Range<u16>| -> String {
xs.map(|x| buf[(x, y)].symbol().to_string()).collect()
};
for y in 0..area.height {
assert_eq!(row(y, 32..80).trim(), "", "row {y} spills past the panel");
}
let words: Vec<String> = (0..area.height)
.flat_map(|y| {
row(y, 1..31)
.split_whitespace()
.map(String::from)
.collect::<Vec<_>>()
})
.collect();
let text = words.join(" ");
assert!(text.contains(msg), "the whole message is on screen: {text}");
}
#[test]
fn feedback_wrapping_splits_long_words_and_caps_the_rows() {
assert_eq!(
wrap_feedback("abcdefghij kl", 4, 4),
vec!["abcd", "efgh", "ij", "kl"]
);
let rows = wrap_feedback(&"word ".repeat(40), 10, 2);
assert_eq!(rows.len(), 2);
assert!(
rows[1].ends_with('…') && rows[1].chars().count() <= 10,
"{rows:?}"
);
assert!(wrap_feedback("anything", 0, 3).is_empty());
}
#[test]
fn short_commit_feedback_stays_on_one_line() {
use ratatui::buffer::Buffer;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 24,
};
let list_top = |feedback: Option<&str>| {
let mut p = SourceControlPanel::new();
p.status.in_repo = true;
p.commit_feedback = feedback.map(String::from);
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
p.last_list_area.y
};
assert_eq!(list_top(Some("[main 548c72d] Merge")), list_top(Some("x")));
}
#[test]
fn header_refresh_pill_absent_without_a_repo() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.status.in_repo = false;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 24,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert_eq!(
p.header_refresh_btn.width, 0,
"no refresh pill in the no-repo empty state",
);
}
#[test]
fn list_layout_orders_conflicts_staged_changes_untracked() {
let mut p = SourceControlPanel::new();
p.entries = vec![
ChangeEntry {
path: "u.txt".into(),
kind: ChangeKind::Untracked,
..Default::default()
},
ChangeEntry {
path: "m.txt".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "s.txt".into(),
kind: ChangeKind::StagedAdded,
..Default::default()
},
ChangeEntry {
path: "c.txt".into(),
kind: ChangeKind::Conflicted,
..Default::default()
},
];
let lines = p.list_layout();
assert!(matches!(
lines[0],
ListLine::Header(ChangeSection::Conflicts)
));
assert!(matches!(lines[2], ListLine::Header(ChangeSection::Staged)));
assert!(matches!(lines[4], ListLine::Header(ChangeSection::Changes)));
assert!(matches!(
lines[6],
ListLine::Header(ChangeSection::Untracked)
));
}
fn buffer_to_string(buf: &Buffer) -> String {
let mut out = String::new();
for y in buf.area.y..buf.area.y + buf.area.height {
for x in buf.area.x..buf.area.x + buf.area.width {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
fn dummy_status_with_branch(name: &str) -> GitStatus {
GitStatus {
in_repo: true,
branch: Some(name.to_string()),
detached_hash: None,
ahead: 0,
behind: 0,
head_oid: None,
ignored: std::sync::Arc::default(),
decorations: std::sync::Arc::default(),
dirty: false,
repo_root: None,
changed_count: 0,
prepared_message: None,
operation: None,
rebasing_branch: None,
}
}
#[test]
fn header_pills_stay_clear_of_a_translated_title() {
use ratatui::buffer::Buffer;
let title = "QUELLCODEVERWALTUNG";
for width in 21..40u16 {
let mut p = SourceControlPanel::new();
p.status.in_repo = true;
let area = Rect {
x: 0,
y: 0,
width,
height: 24,
};
let mut buf = Buffer::empty(area);
crate::i18n::with_test_catalog(&format!(r#"{{"SOURCE CONTROL": "{title}"}}"#), || {
(&mut p).render(area, &mut buf);
});
let inner = p.last_inner;
let header: String = (inner.x..inner.x + inner.width)
.map(|x| buf[(x, inner.y)].symbol())
.collect();
assert!(
header.contains(title),
"width {width}: header pills painted over the title: {header:?}"
);
for btn in [p.header_refresh_btn, p.header_more_btn] {
assert!(
btn.width == 0 || btn.x > inner.x + title.len() as u16,
"width {width}: pill {btn:?} overlaps the title"
);
}
}
}
#[test]
fn header_row_says_source_control_inside_the_panel_not_on_the_outer_border() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let dump = buffer_to_string(&buf);
let inner_top = dump.lines().nth(1).expect("inner row 0");
assert!(
inner_top.contains("SOURCE CONTROL"),
"first inner row must carry SOURCE CONTROL: {inner_top:?}"
);
let outer = dump.lines().next().expect("outer top border");
assert!(
!outer.contains("SOURCE CONTROL"),
"outer border must not carry the title chip: {outer:?}"
);
}
#[test]
fn placeholder_text_never_overflows_past_the_input_box_right_border() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let panel_area = Rect {
x: 0,
y: 0,
width: 28,
height: 30,
};
let buf_area = Rect {
x: 0,
y: 0,
width: 80,
height: 30,
};
let mut buf = Buffer::empty(buf_area);
ratatui::widgets::Widget::render(&mut p, panel_area, &mut buf);
let placeholder_row = p.last_input_area.y + 1;
for x in panel_area.right()..buf_area.right() {
let sym = buf[(x, placeholder_row)].symbol().to_string();
assert!(
sym == " " || sym.is_empty(),
"column {x} (past the SC panel's right edge at {}) carries content: {sym:?} — the placeholder string overflowed the input box and bled into the editor band, exactly the bug the user reported. Use set_stringn with a width cap.",
panel_area.right(),
);
}
}
#[test]
fn typed_message_text_never_overflows_past_the_input_box_right_border() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.message =
"this is a very long commit message that should not overflow the input box at all"
.to_string();
let panel_area = Rect {
x: 0,
y: 0,
width: 28,
height: 30,
};
let buf_area = Rect {
x: 0,
y: 0,
width: 80,
height: 30,
};
let mut buf = Buffer::empty(buf_area);
ratatui::widgets::Widget::render(&mut p, panel_area, &mut buf);
let row = p.last_input_area.y + 1;
for x in panel_area.right()..buf_area.right() {
let sym = buf[(x, row)].symbol().to_string();
assert!(
sym == " " || sym.is_empty(),
"typed message overflowed past the SC panel's right edge at column {x}: {sym:?} — same root cause as the placeholder leak"
);
}
}
#[test]
fn commit_feedback_shows_its_first_line_and_stays_inside_the_panel() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.commit_feedback = Some(
"[main 5a6cd5c] Add per-category report with a subject longer than the panel\n \
3 files changed, 38 insertions(+)\n create mode 100644 report.py"
.to_string(),
);
let panel_area = Rect {
x: 0,
y: 0,
width: 28,
height: 30,
};
let buf_area = Rect {
x: 0,
y: 0,
width: 80,
height: 30,
};
let mut buf = Buffer::empty(buf_area);
ratatui::widgets::Widget::render(&mut p, panel_area, &mut buf);
for y in buf_area.top()..buf_area.bottom() {
for x in panel_area.right()..buf_area.right() {
let sym = buf[(x, y)].symbol();
assert!(
sym == " " || sym.is_empty(),
"cell ({x}, {y}) past the panel's right edge carries {sym:?}"
);
}
}
let panel_text: String = (panel_area.top()..panel_area.bottom())
.flat_map(|y| (panel_area.left()..panel_area.right()).map(move |x| (x, y)))
.map(|pos| buf[pos].symbol().to_string())
.collect();
assert!(panel_text.contains("[main 5a6cd5c] Add"), "{panel_text:?}");
assert!(
!panel_text.contains("changed") && !panel_text.contains("create mode"),
"only git's first line belongs in the panel: {panel_text:?}"
);
}
#[test]
fn a_short_feedback_is_drawn_whole_and_an_error_stays_inside_the_panel() {
use ratatui::buffer::Buffer;
let draw = |feedback: &str, is_error: bool| -> (Buffer, Rect) {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.commit_feedback = Some(feedback.to_string());
p.commit_feedback_is_error = is_error;
let panel_area = Rect::new(0, 0, 28, 30);
let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
ratatui::widgets::Widget::render(&mut p, panel_area, &mut buf);
(buf, panel_area)
};
let text = |buf: &Buffer, area: Rect| -> String {
(area.top()..area.bottom())
.map(|y| {
(area.left()..area.right())
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
};
let (buf, area) = draw("Empty commit message", true);
assert!(text(&buf, area).contains("Empty commit message"));
let (buf, area) = draw(
"error: pathspec 'a-very-long-file-name-that-runs-on.rs' did not match",
true,
);
for y in 0..30 {
for x in area.right()..80 {
let sym = buf[(x, y)].symbol();
assert!(
sym == " " || sym.is_empty(),
"cell ({x}, {y}) past the panel carries {sym:?}"
);
}
}
assert!(text(&buf, area).contains("error: pathspec"));
}
#[test]
fn long_commit_message_keeps_the_caret_visible_and_scrolls_to_show_the_tail() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.focused = true;
let long = "/var/folders/8r/rz52gwd56wz0yw3sqc7xprgm0000gn/T/croft";
p.insert_str(long);
let panel_area = Rect {
x: 0,
y: 0,
width: 28,
height: 30,
};
let mut buf = Buffer::empty(panel_area);
ratatui::widgets::Widget::render(&mut p, panel_area, &mut buf);
assert!(
p.cursor_screen_pos().is_some(),
"the caret must stay visible when the message is longer than the input box; otherwise the user can't see what they're editing and the box feels frozen"
);
let row = p.last_input_area.y + 1;
let rendered: String = (p.last_input_area.x..p.last_input_area.right())
.map(|x| buf[(x, row)].symbol().to_string())
.collect();
assert!(
rendered.contains("croft"),
"the box must scroll horizontally to reveal the tail near the cursor; rendered window was {rendered:?}"
);
}
#[test]
fn home_and_end_move_within_the_carets_line() {
let mut p = SourceControlPanel::new();
p.insert_str("Add rounding\n\nRounds to cents.\nFixes 42");
assert!(p.move_cursor_up());
p.home();
p.insert_char('[');
p.end();
p.insert_char(']');
assert_eq!(p.message, "Add rounding\n\n[Rounds to cents.]\nFixes 42");
let mut p = SourceControlPanel::new();
p.insert_str("a\n\nbody");
assert!(p.move_cursor_up());
p.end();
assert_eq!(p.message_cursor, 2);
p.home();
assert_eq!(p.message_cursor, 2);
}
#[test]
fn single_line_home_end_and_whole_message_moves_are_unchanged() {
let mut p = SourceControlPanel::new();
p.insert_str("one line");
p.home();
assert_eq!(p.message_cursor, 0);
p.end();
assert_eq!(p.message_cursor, 8);
let mut p = SourceControlPanel::new();
p.insert_str("subject\n\nbody\nlast");
assert!(p.move_cursor_up());
p.message_start();
assert_eq!(p.message_cursor, 0);
assert!(p.move_cursor_down());
p.message_end();
assert_eq!(p.message_cursor, p.message.chars().count());
}
#[test]
fn delete_key_forward_deletes_in_the_commit_message() {
let mut p = SourceControlPanel::new();
p.insert_str("abc");
p.home();
p.delete_char();
assert_eq!((p.message.as_str(), p.message_cursor), ("bc", 0));
}
#[test]
fn input_box_is_three_rows_tall_with_a_focus_aware_border() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
assert_eq!(
p.last_input_area.height, 3,
"commit-message input must be 3 rows tall to match the chunky aesthetic"
);
assert!(p.last_input_area.width >= 20);
}
#[test]
fn commit_button_is_chunky_three_row_full_width_block() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
assert_eq!(
p.last_button_area.height, 3,
"Commit button must be 3 rows tall (chunky) like the mockup"
);
assert!(
p.last_button_area.width >= 20,
"Commit button must be near-full-width; got {}",
p.last_button_area.width
);
}
#[test]
fn branch_row_uses_the_source_control_codicon_in_cyan() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let inner = p.last_inner;
let row_y = inner.y + 2;
let mut hit: Option<u16> = None;
for x in inner.x..inner.x + inner.width {
if buf[(x, row_y)].symbol() == "\u{ea68}" {
hit = Some(x);
break;
}
}
let x = hit.expect("branch row must carry the cod-source-control (U+EA68) Y-fork glyph");
let style = buf[(x, row_y)].style();
let expected = ratatui::style::Color::Rgb(0x88, 0xc0, 0xd0);
assert_eq!(
style.fg,
Some(expected),
"branch glyph must render in cyan, matching the VS Code mockup"
);
for x in inner.x..inner.x + inner.width {
let s = buf[(x, row_y)].symbol();
assert_ne!(
s, "\u{eb14}",
"branch row must not carry cod-link-external (U+EB14)"
);
assert_ne!(
s, "\u{ea84}",
"branch row must not carry cod-github (U+EA84)"
);
}
}
#[test]
fn commit_button_uses_rounded_border_corners() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let b = p.last_button_area;
assert!(b.height >= 3 && b.width >= 4, "button must be laid out");
let tl = buf[(b.x, b.y)].symbol().to_string();
let tr = buf[(b.x + b.width - 1, b.y)].symbol().to_string();
let bl = buf[(b.x, b.y + b.height - 1)].symbol().to_string();
let br = buf[(b.x + b.width - 1, b.y + b.height - 1)]
.symbol()
.to_string();
assert_eq!(
tl, "╭",
"top-left commit-button corner must be rounded; got {tl:?}"
);
assert_eq!(
tr, "╮",
"top-right commit-button corner must be rounded; got {tr:?}"
);
assert_eq!(
bl, "╰",
"bottom-left commit-button corner must be rounded; got {bl:?}"
);
assert_eq!(
br, "╯",
"bottom-right commit-button corner must be rounded; got {br:?}"
);
}
#[test]
fn change_section_header_carries_a_count_pill() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "c.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 40,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains("CHANGES"),
"section header must say CHANGES:\n{dump}"
);
assert!(
dump.contains('3'),
"section header must include a count badge of 3:\n{dump}"
);
assert!(
dump.contains('▾') || dump.contains('▿'),
"section header must carry a down chevron:\n{dump}"
);
}
#[test]
fn section_header_shows_green_plus_additions_and_red_minus_deletions() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
additions: 12,
deletions: 3,
},
ChangeEntry {
path: "b.py".into(),
kind: ChangeKind::Modified,
additions: 5,
deletions: 7,
},
],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 40,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains("+17"),
"section header must show total additions +17:\n{dump}"
);
assert!(
dump.contains("-10"),
"section header must show total deletions -10:\n{dump}"
);
let mut plus_cell_is_green = false;
let mut minus_cell_is_red = false;
for y in 0..area.height {
for x in 0..area.width {
let cell = &buf[(x, y)];
let sym = cell.symbol();
let Some(fg) = cell.style().fg else { continue };
let Color::Rgb(r, g, b) = fg else { continue };
if sym == "+" && g > r && g > b {
plus_cell_is_green = true;
}
if sym == "-" && r > g && r > b {
minus_cell_is_red = true;
}
}
}
assert!(
plus_cell_is_green,
"the '+' glyph in the section header must be painted green"
);
assert!(
minus_cell_is_red,
"the '-' glyph in the section header must be painted red"
);
}
#[test]
fn render_in_non_repo_hides_commit_input_and_button_and_list() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default(); let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert_eq!(
p.last_input_area,
Rect::default(),
"input area must stay empty in non-repo"
);
assert_eq!(
p.last_button_area,
Rect::default(),
"commit button area must stay empty in non-repo"
);
assert_eq!(
p.last_list_area,
Rect::default(),
"list area must stay empty in non-repo"
);
}
#[test]
fn empty_state_renders_no_repository_detected_title_and_description() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains("No repository detected"),
"empty-state title missing:\n{dump}"
);
assert!(
dump.contains("Initialize Repository"),
"primary button label missing:\n{dump}"
);
assert!(
dump.contains("Open a folder under Git"),
"description must mention 'Open a folder under Git':\n{dump}"
);
assert!(
dump.contains("tracking changes"),
"description must mention 'tracking changes':\n{dump}"
);
assert!(
!dump.contains("Open Folder"),
"Open Folder button must be gone:\n{dump}"
);
assert!(
!dump.contains("Learn more about Git"),
"Learn more link must be gone:\n{dump}"
);
}
#[test]
fn empty_state_offers_subfolder_repos_instead_of_initialize() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
p.nested_repos = vec![(String::from("sub/"), std::path::PathBuf::from("/w/sub"))];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains("Repositories found in subfolders"),
"title must name the subfolder repos:\n{dump}"
);
assert!(dump.contains("Open sub/"), "open button missing:\n{dump}");
assert!(
!dump.contains("Initialize") && !dump.contains("No repository detected"),
"Initialize must not be offered above a repo:\n{dump}"
);
assert_eq!(p.last_init_repo_button_area, Rect::default());
assert_eq!(p.nested_repo_button_areas.len(), 1);
let (btn, _) = p.nested_repo_button_areas[0].clone();
assert_eq!(
p.click_nested_repo(btn.x + 1, btn.y + 1),
Some(std::path::PathBuf::from("/w/sub"))
);
assert_eq!(p.click_nested_repo(btn.x + 1, btn.y + btn.height), None);
}
#[test]
fn empty_state_lists_one_open_button_per_subfolder_repo() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
p.nested_repos = vec![
(String::from("api/"), std::path::PathBuf::from("/w/api")),
(String::from("web/"), std::path::PathBuf::from("/w/web")),
];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 40,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
dump.contains("Open api/") && dump.contains("Open web/"),
"{dump}"
);
let paths: Vec<_> = p
.nested_repo_button_areas
.iter()
.map(|(_, path)| path.clone())
.collect();
assert_eq!(
paths,
[
std::path::PathBuf::from("/w/api"),
std::path::PathBuf::from("/w/web")
]
);
}
#[test]
fn empty_state_without_subfolder_repos_still_offers_initialize() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
p.nested_repo_button_areas = vec![(
Rect {
x: 1,
y: 1,
width: 5,
height: 3,
},
std::path::PathBuf::from("/stale"),
)];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert!(p.last_init_repo_button_area.width > 0);
assert!(
p.nested_repo_button_areas.is_empty(),
"stale open buttons must not stay clickable"
);
assert_eq!(p.click_nested_repo(2, 2), None);
}
#[test]
fn a_repo_workspace_never_shows_subfolder_open_buttons() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
..GitStatus::default()
};
p.nested_repos = vec![(String::from("sub/"), std::path::PathBuf::from("/w/sub"))];
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert!(p.nested_repo_button_areas.is_empty());
assert!(!buffer_to_string(&buf).contains("Open sub/"));
}
#[test]
fn empty_state_records_button_rect_for_hit_testing() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert!(
p.last_init_repo_button_area.width > 0 && p.last_init_repo_button_area.height > 0,
"Initialize Repository button rect must be tracked"
);
}
#[test]
fn empty_state_init_button_paints_a_visible_label_at_narrow_widths() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 40,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let btn = p.last_init_repo_button_area;
assert!(
btn.width > 0 && btn.height > 0,
"init-repo button must be tracked"
);
let label_y = btn.y + btn.height / 2;
let mut row = String::new();
for x in btn.x..btn.x + btn.width {
row.push_str(buf[(x, label_y)].symbol());
}
let trimmed = row.trim();
assert!(
!trimmed.is_empty() && trimmed.chars().any(|c| c.is_alphabetic()),
"init-repo button row must carry a visible label, got {row:?}"
);
}
#[test]
fn empty_state_description_wraps_to_card_width_no_mid_word_truncation() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
let area = Rect {
x: 0,
y: 0,
width: 30,
height: 40,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
!dump.contains("Open a folder under G\n"),
"description must NOT be hard-truncated mid-word ('under G'):\n{dump}"
);
assert!(
!dump.contains("repository to start t\n"),
"description must NOT be hard-truncated mid-word ('start t'):\n{dump}"
);
}
#[test]
fn empty_state_illustration_does_not_use_arrow_up_codicon() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(
!dump.contains('\u{eaa1}'),
"empty-state must NOT carry U+EAA1 (cod-arrow-up); that was the broken glyph"
);
assert!(
dump.contains('\u{25cf}'),
"rich illustration must paint ● git nodes"
);
}
#[test]
fn click_init_repo_button_returns_true_only_inside_the_rect() {
let mut p = SourceControlPanel::new();
p.last_init_repo_button_area = Rect {
x: 5,
y: 10,
width: 30,
height: 3,
};
assert!(p.click_init_repo_button(20, 11));
assert!(!p.click_init_repo_button(40, 11));
assert!(!p.click_init_repo_button(20, 20));
}
#[test]
fn change_rows_use_a_subtle_row_tint_not_darker_than_panel_bg() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
}],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let bad = ratatui::style::Color::Rgb(0x16, 0x1b, 0x25);
for y in 0..area.height {
for x in 0..area.width {
assert_ne!(
buf[(x, y)].style().bg,
Some(bad),
"no cell may carry the darker-than-panel row bg ({bad:?}) — that's the colour the user complained about; cell at ({x},{y})"
);
}
}
}
#[test]
fn clicking_a_change_entry_highlights_it_with_a_visible_row_bg() {
use ratatui::buffer::Buffer;
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 30,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let target_y = (0..area.height)
.find(|y| {
let mut row = String::new();
for x in 0..area.width {
row.push_str(buf[(x, *y)].symbol());
}
row.contains("b.py")
})
.expect("b.py row must render");
p.select_change_at(target_y);
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let mut selected_has_bg = false;
for x in 0..area.width {
if let Some(bg) = buf[(x, target_y)].style().bg
&& bg != ratatui::style::Color::Reset
{
selected_has_bg = true;
break;
}
}
assert!(
selected_has_bg,
"the row of the clicked entry must carry a visible bg highlight"
);
}
#[test]
fn rendering_at_narrow_widths_does_not_panic() {
use ratatui::buffer::Buffer;
for width in 0u16..40 {
for height in 0u16..30 {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: ".idea/".into(),
kind: ChangeKind::Untracked,
..Default::default()
},
],
);
let area = Rect {
x: 0,
y: 0,
width,
height,
};
if area.width == 0 || area.height == 0 {
continue;
}
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
}
}
}
#[test]
fn repositories_overview_renders_rows_and_maps_clicks() {
let mut p = SourceControlPanel::new();
p.status = dummy_status_with_branch("trunk");
p.repositories = vec![
RepoRow {
label: String::from("gitb"),
branch: Some(String::from("trunk")),
changes: 1,
active: true,
workspace_root: std::path::PathBuf::from("/w/gitb"),
},
RepoRow {
label: String::from("gitc"),
branch: Some(String::from("dev")),
changes: 1,
active: false,
workspace_root: std::path::PathBuf::from("/w/gitc"),
},
];
let area = Rect {
x: 0,
y: 0,
width: 34,
height: 20,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let dump = buffer_to_string(&buf);
assert!(dump.contains("REPOSITORIES"), "{dump}");
assert!(dump.contains("gitb") && dump.contains("gitc"), "{dump}");
let (rect, root) = p.repo_row_areas[1].clone();
assert_eq!(root, std::path::PathBuf::from("/w/gitc"));
assert_eq!(
p.click_repository(rect.x + 2, rect.y),
Some(std::path::PathBuf::from("/w/gitc")),
"a click inside the second row maps to its folder"
);
assert_eq!(p.click_repository(rect.x + 2, rect.y + 10), None);
}
fn merging(message: Option<&str>) -> GitStatus {
GitStatus {
prepared_message: message.map(String::from),
..dummy_status_with_branch("main")
}
}
#[test]
fn a_merge_in_progress_fills_an_empty_message_box() {
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("Merge branch 'other'")), Vec::new());
assert_eq!(p.message, "Merge branch 'other'");
assert_eq!(p.message_cursor, p.message.chars().count());
p.set_status(merging(None), Vec::new());
assert_eq!(p.message, "", "the merge was committed or aborted");
}
#[test]
fn a_prepared_message_with_a_body_fills_the_whole_message() {
let mut p = SourceControlPanel::new();
let prepared = "Revert \"x\"\n\nThis reverts commit abc.";
p.set_status(merging(Some(prepared)), Vec::new());
assert_eq!(p.message, prepared);
assert_eq!(p.message_cursor, p.message.chars().count());
p.set_status(merging(Some(prepared)), Vec::new());
assert_eq!(p.message, prepared, "a refresh doesn't seed it twice");
p.set_status(merging(None), Vec::new());
assert_eq!(p.message, "", "the revert was committed or aborted");
}
#[test]
fn an_edited_body_is_kept_when_the_revert_ends() {
let mut p = SourceControlPanel::new();
p.set_status(
merging(Some("Revert \"x\"\n\nThis reverts commit abc.")),
Vec::new(),
);
p.insert_str(" It broke checkout.");
p.set_status(merging(None), Vec::new());
assert_eq!(
p.message,
"Revert \"x\"\n\nThis reverts commit abc. It broke checkout."
);
}
#[test]
fn a_prepared_message_never_replaces_typed_text() {
let mut p = SourceControlPanel::new();
p.insert_str("my own words");
p.set_status(merging(Some("Merge branch 'other'")), Vec::new());
assert_eq!(p.message, "my own words");
p.set_status(merging(None), Vec::new());
assert_eq!(p.message, "my own words");
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("Merge branch 'other'")), Vec::new());
p.insert_str(" into main");
p.set_status(merging(None), Vec::new());
assert_eq!(p.message, "Merge branch 'other' into main");
}
#[test]
fn the_template_comes_back_after_each_commit() {
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("PROJ-:\n\nWhy:")), Vec::new());
assert_eq!(p.message, "PROJ-:\n\nWhy:");
p.insert_str(" because");
p.clear_after_commit();
assert_eq!(p.message, "");
p.set_status(merging(Some("PROJ-:\n\nWhy:")), Vec::new());
assert_eq!(p.message, "PROJ-:\n\nWhy:", "seeded for the next commit");
}
#[test]
fn an_untouched_seed_follows_the_repository() {
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("A-:")), Vec::new());
p.set_status(merging(Some("B-:")), Vec::new());
assert_eq!(p.message, "B-:");
p.insert_str(" edited");
p.set_status(merging(Some("A-:")), Vec::new());
assert_eq!(p.message, "B-: edited");
}
#[test]
fn a_changed_template_never_replaces_typed_text() {
let mut p = SourceControlPanel::new();
p.insert_str("fix: my words");
p.set_status(merging(Some("PROJ-:")), Vec::new());
p.set_status(merging(Some("TEAM-:")), Vec::new());
assert_eq!(p.message, "fix: my words");
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("PROJ-:")), Vec::new());
p.clear_message();
p.set_status(merging(Some("PROJ-:")), Vec::new());
assert_eq!(p.message, "");
}
#[test]
fn a_cleared_seed_is_not_refilled_on_the_next_refresh() {
let mut p = SourceControlPanel::new();
p.set_status(merging(Some("Merge branch 'other'")), Vec::new());
p.clear_message();
p.set_status(merging(Some("Merge branch 'other'")), Vec::new());
assert_eq!(p.message, "", "the user emptied it on purpose");
}
#[test]
fn no_merge_leaves_an_empty_box_empty() {
let mut p = SourceControlPanel::new();
p.set_status(merging(None), Vec::new());
assert_eq!(p.message, "");
}
#[test]
fn render_in_repo_paints_input_and_button() {
use crate::git::GitStatus;
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
branch: Some("main".into()),
..Default::default()
};
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 16,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert!(
p.last_input_area.height > 0,
"input area must paint when in_repo"
);
assert!(
p.last_button_area.height > 0,
"button area must paint when in_repo"
);
}
#[test]
fn cursor_screen_pos_is_none_when_not_focused() {
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
branch: Some("main".into()),
..Default::default()
};
p.focused = false;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 16,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert_eq!(
p.cursor_screen_pos(),
None,
"caret must hide when the panel is not focused"
);
}
#[test]
fn cursor_screen_pos_is_none_when_no_repo() {
let mut p = SourceControlPanel::new();
p.status = GitStatus::default();
p.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 30,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
assert_eq!(
p.cursor_screen_pos(),
None,
"caret must hide when the panel is in the no-repo empty state (no input box painted)"
);
}
#[test]
fn cursor_screen_pos_lands_at_first_text_cell_when_message_is_empty() {
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
branch: Some("main".into()),
..Default::default()
};
p.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 16,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let r = p.last_input_area;
assert!(r.width >= 3 && r.height == 3, "input must be laid out");
let (cx, cy) = p
.cursor_screen_pos()
.expect("focused, in repo → caret must report a cell");
assert_eq!(
(cx, cy),
(r.x + 2, r.y + 1),
"empty message caret sits at the input's first inner text cell (one pad cell after the rounded left border)"
);
}
#[test]
fn cursor_screen_pos_advances_one_cell_per_inserted_char() {
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
branch: Some("main".into()),
..Default::default()
};
p.focused = true;
let area = Rect {
x: 0,
y: 0,
width: 40,
height: 16,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
p.insert_str("fix");
let r = p.last_input_area;
let (cx, cy) = p.cursor_screen_pos().expect("caret must report a cell");
assert_eq!(
(cx, cy),
(r.x + 2 + 3, r.y + 1),
"after typing 3 chars the caret sits 3 cells past the first text cell"
);
}
#[test]
fn cursor_screen_pos_is_none_before_first_render() {
let mut p = SourceControlPanel::new();
p.status = GitStatus {
in_repo: true,
branch: Some("main".into()),
..Default::default()
};
p.focused = true;
assert_eq!(
p.cursor_screen_pos(),
None,
"caret must hide before the first render (last_input_area is still default)"
);
}
#[test]
fn selected_unstaged_row_paints_discard_and_stage_icons_before_the_badge() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![ChangeEntry {
path: "ch.py".into(),
kind: ChangeKind::Modified,
..Default::default()
}],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let row_y = (area.y..area.y + area.height)
.find(|y| {
let mut row = String::new();
for x in area.x..area.x + area.width {
row.push_str(buf[(x, *y)].symbol());
}
row.contains("ch.py")
})
.expect("ch.py row must render");
p.select_change_at(row_y);
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let actions = p
.last_row_actions
.expect("selected unstaged row must record action hit rects");
assert_eq!(actions.entry_idx, 0);
assert_eq!(
buf[(actions.discard.x, actions.discard.y)].symbol(),
DISCARD_GLYPH.to_string().as_str(),
"discard icon must paint at the recorded hit cell"
);
assert_eq!(
buf[(actions.stage.x, actions.stage.y)].symbol(),
STAGE_GLYPH.to_string().as_str(),
"stage icon must paint at the recorded hit cell"
);
assert!(actions.discard.x < actions.stage.x);
}
#[test]
fn unselected_rows_paint_no_action_icons() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b.py".into(),
kind: ChangeKind::Modified,
..Default::default()
},
],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
assert!(
p.last_row_actions.is_none(),
"no selection ⇒ no action icons"
);
let dump = buffer_to_string(&buf);
assert!(
!dump.contains(DISCARD_GLYPH),
"discard glyph must not paint on any row when nothing is selected: {dump}"
);
}
#[test]
fn selected_staged_row_exposes_only_an_unstage_action() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![ChangeEntry {
path: "s.py".into(),
kind: ChangeKind::StagedModified,
..Default::default()
}],
);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let row_y = (area.y..area.y + area.height)
.find(|y| {
let mut row = String::new();
for x in area.x..area.x + area.width {
row.push_str(buf[(x, *y)].symbol());
}
row.contains("s.py")
})
.expect("s.py row must render");
p.select_change_at(row_y);
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let actions = p
.last_row_actions
.expect("a selected staged row exposes the unstage action");
assert!(actions.unstage.width > 0, "staged rows offer Unstage");
assert_eq!(
actions.stage,
Rect::default(),
"a staged row never offers Stage (it is already staged)"
);
assert_eq!(
actions.discard,
Rect::default(),
"Discard lives on the Changes section, not Staged"
);
assert_eq!(
buf[(actions.unstage.x, actions.unstage.y)].symbol(),
UNSTAGE_GLYPH.to_string(),
);
}
#[test]
fn click_discard_action_returns_entry_idx_only_inside_the_rect() {
let mut p = SourceControlPanel::new();
p.last_row_actions = Some(RowActionAreas {
entry_idx: 7,
discard: Rect {
x: 10,
y: 5,
width: 1,
height: 1,
},
stage: Rect {
x: 12,
y: 5,
width: 1,
height: 1,
},
unstage: Rect::default(),
});
assert_eq!(p.click_discard_action(10, 5), Some(7));
assert_eq!(
p.click_discard_action(12, 5),
None,
"stage cell is not discard"
);
assert_eq!(
p.click_discard_action(11, 5),
None,
"gap cell is not discard"
);
assert_eq!(p.click_discard_action(10, 6), None, "wrong row");
}
#[test]
fn click_stage_action_returns_entry_idx_only_inside_the_rect() {
let mut p = SourceControlPanel::new();
p.last_row_actions = Some(RowActionAreas {
entry_idx: 3,
discard: Rect {
x: 10,
y: 5,
width: 1,
height: 1,
},
stage: Rect {
x: 12,
y: 5,
width: 1,
height: 1,
},
unstage: Rect::default(),
});
assert_eq!(p.click_stage_action(12, 5), Some(3));
assert_eq!(
p.click_stage_action(10, 5),
None,
"discard cell is not stage"
);
assert_eq!(p.click_stage_action(13, 5), None, "outside stage rect");
}
#[test]
fn click_unstage_action_returns_entry_idx_only_inside_the_rect() {
let mut p = SourceControlPanel::new();
p.last_row_actions = Some(RowActionAreas {
entry_idx: 4,
discard: Rect::default(),
stage: Rect::default(),
unstage: Rect {
x: 12,
y: 5,
width: 1,
height: 1,
},
});
assert_eq!(p.click_unstage_action(12, 5), Some(4));
assert_eq!(
p.click_unstage_action(11, 5),
None,
"gap cell is not unstage"
);
assert_eq!(p.click_unstage_action(12, 6), None, "wrong row");
}
#[test]
fn action_icons_are_suppressed_at_narrow_widths_so_the_path_stays_legible() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![ChangeEntry {
path: "a.py".into(),
kind: ChangeKind::Modified,
..Default::default()
}],
);
p.selected_change = Some(0);
let area = Rect {
x: 0,
y: 0,
width: 10,
height: 60,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
assert!(
p.last_row_actions.is_none(),
"narrow rows must skip the action icons rather than overlap the path"
);
}
#[test]
fn select_all_changes_loads_every_entry_into_multi_selection() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "c".into(),
kind: ChangeKind::Untracked,
..Default::default()
},
],
);
let n = p.select_all_changes();
assert_eq!(n, 3);
assert!(p.multi_selection.contains(&0));
assert!(p.multi_selection.contains(&1));
assert!(p.multi_selection.contains(&2));
}
#[test]
fn clicking_a_row_resets_multi_selection_to_just_that_row() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b".into(),
kind: ChangeKind::Modified,
..Default::default()
},
],
);
p.select_all_changes();
assert_eq!(p.multi_selection.len(), 2);
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let row_y = (area.y..area.y + area.height)
.find(|y| {
let mut row = String::new();
for x in area.x..area.x + area.width {
row.push_str(buf[(x, *y)].symbol());
}
row.contains("b") && !row.contains("a")
})
.expect("b row must render");
p.select_change_at(row_y);
assert_eq!(
p.multi_selection.len(),
1,
"single click narrows to one row"
);
}
fn change(path: &str, kind: ChangeKind) -> ChangeEntry {
ChangeEntry {
path: path.into(),
kind,
..Default::default()
}
}
#[test]
fn arrows_walk_the_change_list_in_drawn_order_and_keep_it_in_view() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
change("new.txt", ChangeKind::Untracked),
change("edit.txt", ChangeKind::Modified),
change("added.txt", ChangeKind::StagedAdded),
],
);
p.focused = true;
p.last_input_area = Rect::new(0, 0, 20, 3);
p.last_list_area = Rect::new(0, 10, 20, 2);
assert!(p.cursor_screen_pos().is_some());
assert!(p.focus_list());
assert!(p.cursor_screen_pos().is_none(), "the list hides the caret");
assert_eq!(p.selected_change, Some(2), "the staged row is drawn first");
let mut walked = Vec::new();
for _ in 0..3 {
assert!(p.move_selection(false));
walked.push((p.selected_change, p.scroll));
}
assert_eq!(walked, [(Some(1), 2), (Some(0), 4), (Some(0), 4)]);
assert!(p.move_selection(true) && p.move_selection(true));
assert_eq!((p.selected_change, p.scroll), (Some(2), 0));
assert!(!p.move_selection(true), "Up from the first row leaves");
}
#[test]
fn a_refresh_keeps_the_selection_on_its_file() {
let mut p = SourceControlPanel::new();
let main = || dummy_status_with_branch("main");
p.set_status(
main(),
vec![
change("seed.txt", ChangeKind::Modified),
change("scratch.txt", ChangeKind::Untracked),
],
);
p.selected_change = Some(1);
p.list_focused = true;
p.set_status(
main(),
vec![
change("scratch.txt", ChangeKind::StagedAdded),
change("seed.txt", ChangeKind::Modified),
],
);
assert_eq!(p.selected_change, Some(0));
let seed = |kind| change("seed.txt", kind);
let rows = vec![seed(ChangeKind::StagedModified), seed(ChangeKind::Modified)];
p.set_status(main(), rows.clone());
p.selected_change = Some(1);
p.set_status(
main(),
[vec![change("a", ChangeKind::Untracked)], rows].concat(),
);
assert_eq!(p.selected_change, Some(2));
p.set_status(main(), Vec::new());
assert!(!p.list_focused, "an empty list gives the keyboard back");
}
#[test]
fn a_refresh_keeps_the_multi_selection_on_its_files() {
let mut p = SourceControlPanel::new();
let main = || dummy_status_with_branch("main");
p.set_status(
main(),
vec![
change("seed.txt", ChangeKind::Modified),
change("scratch.txt", ChangeKind::Untracked),
change("gone.txt", ChangeKind::Untracked),
],
);
p.multi_selection = [1, 2].into_iter().collect();
p.set_status(
main(),
vec![
change("scratch.txt", ChangeKind::StagedAdded),
change("seed.txt", ChangeKind::Modified),
],
);
assert_eq!(p.multi_selection, [0].into_iter().collect());
}
#[test]
fn multi_selected_rows_paint_a_visible_row_bg_even_when_not_primary() {
let mut p = SourceControlPanel::new();
p.set_status(
dummy_status_with_branch("main"),
vec![
ChangeEntry {
path: "a".into(),
kind: ChangeKind::Modified,
..Default::default()
},
ChangeEntry {
path: "b".into(),
kind: ChangeKind::Modified,
..Default::default()
},
],
);
p.select_all_changes();
p.selected_change = Some(0); let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
let row_b_y = (area.y..area.y + area.height)
.find(|y| {
let mut row = String::new();
for x in area.x..area.x + area.width {
row.push_str(buf[(x, *y)].symbol());
}
row.contains('b') && !row.contains('a')
})
.expect("b row must render");
let mut secondary_has_bg = false;
for x in 0..area.width {
if let Some(bg) = buf[(x, row_b_y)].style().bg
&& bg != Color::Reset
{
secondary_has_bg = true;
break;
}
}
assert!(
secondary_has_bg,
"secondary multi-selected rows must paint a visible row bg so the Cmd+S scope is obvious"
);
}
#[test]
fn split_commit_button_records_a_separate_caret_rect_at_default_widths() {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 20,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(&mut p, area, &mut buf);
assert!(
p.last_button_area.width > 0,
"main commit button must paint"
);
assert!(
p.last_commit_caret_area.width > 0,
"split caret must paint alongside the main button at panel widths >= 20"
);
assert_eq!(
p.last_commit_caret_area.x,
p.last_button_area.x + p.last_button_area.width + 1
);
let caret_mid = (
p.last_commit_caret_area.x + p.last_commit_caret_area.width / 2,
p.last_commit_caret_area.y + 1,
);
assert!(!p.click_button(caret_mid.0, caret_mid.1));
assert!(p.click_commit_caret(caret_mid.0, caret_mid.1));
}
#[test]
fn click_commit_menu_item_dispatches_on_recorded_rects() {
let mut p = SourceControlPanel::new();
p.commit_menu_item_areas = vec![
(
Rect {
x: 10,
y: 5,
width: 20,
height: 1,
},
CommitMenuItem::CommitAndPush,
),
(
Rect {
x: 10,
y: 6,
width: 20,
height: 1,
},
CommitMenuItem::Push,
),
(
Rect {
x: 10,
y: 7,
width: 20,
height: 1,
},
CommitMenuItem::ViewStagedDiff,
),
(
Rect {
x: 10,
y: 8,
width: 20,
height: 1,
},
CommitMenuItem::ViewDefaultBranchDiff,
),
];
assert_eq!(
p.click_commit_menu_item(15, 5),
Some(CommitMenuItem::CommitAndPush)
);
assert_eq!(p.click_commit_menu_item(15, 6), Some(CommitMenuItem::Push));
assert_eq!(
p.click_commit_menu_item(15, 7),
Some(CommitMenuItem::ViewStagedDiff)
);
assert_eq!(
p.click_commit_menu_item(15, 8),
Some(CommitMenuItem::ViewDefaultBranchDiff)
);
assert_eq!(p.click_commit_menu_item(5, 5), None, "outside the rects");
assert_eq!(p.click_commit_menu_item(15, 9), None, "below the menu");
}
#[test]
fn commit_menu_item_label_inlines_default_branch_for_view_diff_item() {
assert_eq!(
CommitMenuItem::ViewDefaultBranchDiff.label("trunk"),
"View Changes vs trunk"
);
assert_eq!(
CommitMenuItem::CommitAndPush.label("anything"),
"Commit & Push"
);
assert_eq!(CommitMenuItem::Push.label("anything"), "Push");
assert_eq!(
CommitMenuItem::ViewStagedDiff.label("anything"),
"View Staged Changes"
);
}
#[test]
fn commit_menu_items_carry_their_codicon_glyph() {
assert_eq!(CommitMenuItem::CommitAndPush.icon(), '\u{eac3}'); assert_eq!(CommitMenuItem::Push.icon(), '\u{eaa1}'); assert_eq!(CommitMenuItem::ViewStagedDiff.icon(), '\u{eae1}'); assert_eq!(CommitMenuItem::ViewPreviousCommitDiff.icon(), '\u{eafd}'); assert_eq!(CommitMenuItem::ViewDefaultBranchDiff.icon(), '\u{eafd}'); }
#[test]
fn changes_count_returns_entry_total() {
let mut p = SourceControlPanel::new();
assert_eq!(p.changes_count(), 0);
p.entries.push(ChangeEntry {
path: "x".into(),
kind: ChangeKind::Modified,
..Default::default()
});
p.entries.push(ChangeEntry {
path: "y".into(),
kind: ChangeKind::Untracked,
..Default::default()
});
assert_eq!(p.changes_count(), 2);
}
fn render_rows(p: &mut SourceControlPanel) -> Vec<String> {
render_rows_in(p, 30)
}
fn render_rows_in(p: &mut SourceControlPanel, height: u16) -> Vec<String> {
use ratatui::buffer::Buffer;
let area = Rect {
x: 0,
y: 0,
width: 40,
height,
};
let mut buf = Buffer::empty(area);
ratatui::widgets::Widget::render(p, area, &mut buf);
(0..area.height)
.map(|y| (0..area.width).map(|x| buf[(x, y)].symbol()).collect())
.collect()
}
#[test]
fn pasted_line_breaks_are_kept_as_newlines() {
let mut p = SourceControlPanel::new();
p.insert_str("a\r\n\r\nb\rc\nd");
assert_eq!(p.message, "a\n\nb\nc\nd");
assert_eq!(p.message_cursor, p.message.chars().count());
}
#[test]
fn the_message_box_shows_each_line_on_its_own_row() {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.focused = true;
p.insert_str("subject\n\nbody");
let rows = render_rows(&mut p);
let input = p.last_input_area;
assert_eq!(input.height, 5, "three lines plus the border");
let row = |n: u16| rows[(input.y + 1 + n) as usize].clone();
assert!(row(0).contains("subject"), "{rows:#?}");
assert!(!row(1).contains("body") && !row(1).contains("subject"));
assert!(row(2).contains("body"), "{rows:#?}");
assert_eq!(p.cursor_screen_pos(), Some((input.x + 2 + 4, input.y + 3)));
}
#[test]
fn a_long_message_scrolls_to_the_caret_line() {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.focused = true;
let text: Vec<String> = (1..=12).map(|n| format!("line{n}")).collect();
p.insert_str(&text.join("\n"));
let rows = render_rows(&mut p);
let input = p.last_input_area;
assert_eq!(input.height, 2 + MESSAGE_MAX_ROWS as u16);
let last = rows[(input.y + input.height - 2) as usize].clone();
assert!(last.contains("line12"), "{rows:#?}");
assert!(!rows.iter().any(|r| r.contains("line1 ")), "{rows:#?}");
let (_, caret_y) = p.cursor_screen_pos().unwrap();
assert_eq!(caret_y, input.y + input.height - 2);
}
fn long_message_panel(lines: usize) -> SourceControlPanel {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.focused = true;
let text: Vec<String> = (1..=lines).map(|n| format!("line{n}")).collect();
p.insert_str(&text.join("\n"));
p
}
#[test]
fn a_long_message_leaves_room_for_the_commit_button() {
let mut p = long_message_panel(5);
let rows = render_rows_in(&mut p, 16);
let button = p.last_button_area;
assert_eq!(button.height, 3, "{rows:#?}");
assert!(button.y + button.height <= 16, "{button:?}");
assert!(
rows[(button.y + 1) as usize].contains("Commit"),
"{rows:#?}"
);
let input = p.last_input_area;
assert!(input.y + input.height < button.y, "{input:?} {button:?}");
let (_, caret_y) = p.cursor_screen_pos().unwrap();
assert!(rows[caret_y as usize].contains("line5"), "{rows:#?}");
}
#[test]
fn a_long_message_leaves_room_for_the_change_list() {
let mut p = long_message_panel(6);
let rows = render_rows_in(&mut p, 20);
assert!(
p.last_list_area.height >= 2,
"{:?} {rows:#?}",
p.last_list_area
);
assert!(p.last_list_area.y + p.last_list_area.height <= 20);
}
#[test]
fn up_and_down_move_between_message_lines() {
let mut p = SourceControlPanel::new();
p.insert_str("abcdef\nxy\nlonger");
assert!(p.move_cursor_up(), "from the last line up");
assert_eq!(
p.message_cursor,
7 + 2,
"column 6 clamps to the end of 'xy'"
);
assert!(p.move_cursor_up());
assert_eq!(p.message_cursor, 2);
assert!(!p.move_cursor_up(), "the first line has nothing above");
assert!(p.move_cursor_down());
assert!(p.move_cursor_down());
assert_eq!(p.message_cursor, 10 + 2);
assert!(!p.move_cursor_down(), "the last line has nothing below");
}
#[test]
fn a_one_line_message_keeps_the_three_row_box() {
let mut p = SourceControlPanel::new();
p.set_status(dummy_status_with_branch("main"), Vec::new());
p.insert_str("just a subject");
render_rows(&mut p);
assert_eq!(p.last_input_area.height, 3);
}
}