use std::collections::HashSet;
use std::path::PathBuf;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Paragraph, Widget},
};
use crate::lsp::manager::DiagnosticSeverity;
use crate::theme::Theme;
use crate::widgets::scrollbar;
const COLOR_HEADER: Color = Color::Rgb(0xE8, 0xEE, 0xF8);
const COLOR_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const COLOR_MSG: Color = Color::Rgb(0xCC, 0xCC, 0xCC);
const COLOR_ERROR: Color = Color::Rgb(0xf1, 0x4c, 0x4c);
const COLOR_WARNING: Color = Color::Rgb(0xcc, 0xa7, 0x00);
const COLOR_INFO: Color = Color::Rgb(0x3b, 0x9e, 0xff);
const GLYPH_ERROR: char = '\u{ea87}';
const GLYPH_WARNING: char = '\u{ea6c}';
const GLYPH_INFO: char = '\u{ea74}';
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProblemItem {
pub line: u32,
pub col: u32,
pub col_utf16: bool,
pub severity: DiagnosticSeverity,
pub message: String,
pub source: String,
pub code: Option<crate::lsp::manager::DiagnosticCode>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProblemGroup {
pub path: PathBuf,
pub name: String,
pub rel_dir: String,
pub items: Vec<ProblemItem>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum RenderRow {
Header(usize),
Diag(usize, usize),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ProblemScope {
OpenFiles,
#[default]
WholeProject,
}
impl ProblemScope {
pub fn label(self) -> &'static str {
match self {
Self::OpenFiles => "Open Files",
Self::WholeProject => "Whole Project",
}
}
pub fn next(self) -> Self {
match self {
Self::OpenFiles => Self::WholeProject,
Self::WholeProject => Self::OpenFiles,
}
}
pub fn to_config(self) -> &'static str {
match self {
Self::OpenFiles => "open_files",
Self::WholeProject => "whole_project",
}
}
pub fn from_config(s: &str) -> Self {
let norm = s.trim().to_ascii_lowercase().replace([' ', '-'], "_");
match norm.as_str() {
"open" | "open_files" | "openfiles" => Self::OpenFiles,
"whole_project" | "wholeproject" | "project" | "all" => Self::WholeProject,
_ => Self::WholeProject,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProblemFilter {
All,
Errors,
Warnings,
}
impl ProblemFilter {
fn next(self) -> Self {
match self {
Self::All => Self::Errors,
Self::Errors => Self::Warnings,
Self::Warnings => Self::All,
}
}
fn label(self) -> &'static str {
match self {
Self::All => "All",
Self::Errors => "Errors",
Self::Warnings => "Errors & Warnings",
}
}
fn keeps(self, sev: DiagnosticSeverity) -> bool {
match self {
Self::All => true,
Self::Errors => sev == DiagnosticSeverity::Error,
Self::Warnings => {
matches!(sev, DiagnosticSeverity::Error | DiagnosticSeverity::Warning)
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProblemHit {
Header(PathBuf),
Diagnostic {
path: PathBuf,
line: u32,
col: u32,
col_utf16: bool,
},
}
const FILTER_CHIP_CHARS: usize = 24;
pub struct ProblemsPanel {
groups: Vec<ProblemGroup>,
collapsed: HashSet<PathBuf>,
scroll: usize,
filter: ProblemFilter,
pub text_filter: String,
group_by_file: bool,
pub scope: ProblemScope,
pub focus_gradient: bool,
pub theme: Theme,
pub focused: bool,
pub hover_pointer: Option<(u16, u16)>,
pub last_area: Rect,
pub last_scrollbar: Rect,
pub fixing: Option<(PathBuf, u32)>,
pub fix_glyph: &'static str,
filter_rect: Rect,
group_rect: Rect,
rows: Vec<RenderRow>,
first_row_y: u16,
visible_rows: u16,
viewport_rows: u16,
}
impl ProblemsPanel {
pub fn new() -> Self {
Self {
groups: Vec::new(),
collapsed: HashSet::new(),
scroll: 0,
filter: ProblemFilter::All,
text_filter: String::new(),
group_by_file: true,
scope: ProblemScope::default(),
focus_gradient: false,
theme: Theme::default(),
focused: false,
hover_pointer: None,
last_area: Rect::default(),
last_scrollbar: Rect::default(),
fixing: None,
fix_glyph: "",
filter_rect: Rect::default(),
group_rect: Rect::default(),
rows: Vec::new(),
first_row_y: 0,
visible_rows: 0,
viewport_rows: 0,
}
}
pub fn groups(&self) -> &[ProblemGroup] {
&self.groups
}
pub fn set_groups(&mut self, groups: Vec<ProblemGroup>) -> bool {
if self.groups == groups {
return false;
}
self.collapsed
.retain(|p| groups.iter().any(|g| &g.path == p));
self.groups = groups;
self.scroll = self.scroll.min(self.max_scroll());
true
}
pub fn is_empty(&self) -> bool {
self.groups.is_empty()
}
pub fn total_count(&self) -> usize {
self.groups.iter().map(|g| g.items.len()).sum()
}
pub fn top_diagnostic(&self) -> Option<(&ProblemGroup, &ProblemItem)> {
let mut row = 0usize;
for (g, items) in self.visible_groups() {
let group = &self.groups[g];
if self.group_by_file {
row += 1;
if self.collapsed.contains(&group.path) {
continue;
}
}
for i in items {
if row >= self.scroll {
return Some((group, &group.items[i]));
}
row += 1;
}
}
None
}
pub fn error_count(&self) -> usize {
self.severity_count(DiagnosticSeverity::Error)
}
pub fn warning_count(&self) -> usize {
self.severity_count(DiagnosticSeverity::Warning)
}
fn severity_count(&self, want: DiagnosticSeverity) -> usize {
self.groups
.iter()
.flat_map(|g| g.items.iter())
.filter(|i| i.severity == want)
.count()
}
pub fn toggle_collapse(&mut self, path: &PathBuf) {
if !self.collapsed.remove(path) {
self.collapsed.insert(path.clone());
}
self.scroll = self.scroll.min(self.max_scroll());
}
pub fn scroll_down(&mut self, n: usize) {
self.scroll = (self.scroll + n).min(self.max_scroll());
}
pub fn scroll_up(&mut self, n: usize) {
self.scroll = self.scroll.saturating_sub(n);
}
fn max_scroll(&self) -> usize {
self.total_rows()
.saturating_sub(self.viewport_rows as usize)
}
fn keeps_item(&self, group: &ProblemGroup, it: &ProblemItem) -> bool {
if !self.filter.keeps(it.severity) {
return false;
}
if self.text_filter.is_empty() {
return true;
}
let needle = self.text_filter.to_lowercase();
it.message.to_lowercase().contains(&needle)
|| it
.code
.as_ref()
.is_some_and(|c| c.label(&it.source).to_lowercase().contains(&needle))
|| group
.path
.to_string_lossy()
.to_lowercase()
.contains(&needle)
}
pub fn push_filter_char(&mut self, c: char) {
self.text_filter.push(c);
self.scroll = 0;
}
pub fn pop_filter_char(&mut self) {
self.text_filter.pop();
self.scroll = 0;
}
pub fn clear_text_filter(&mut self) -> bool {
if self.text_filter.is_empty() {
return false;
}
self.text_filter.clear();
self.scroll = 0;
true
}
fn visible_groups(&self) -> Vec<(usize, Vec<usize>)> {
self.groups
.iter()
.enumerate()
.filter_map(|(g, group)| {
let items: Vec<usize> = group
.items
.iter()
.enumerate()
.filter(|(_, it)| self.keeps_item(group, it))
.map(|(i, _)| i)
.collect();
(!items.is_empty()).then_some((g, items))
})
.collect()
}
fn total_rows(&self) -> usize {
self.visible_groups()
.iter()
.map(|(g, items)| {
if !self.group_by_file {
items.len()
} else if self.collapsed.contains(&self.groups[*g].path) {
1
} else {
1 + items.len()
}
})
.sum()
}
pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
let Some(metrics) = scrollbar::vertical_metrics(
self.last_scrollbar,
self.total_rows(),
self.viewport_rows as usize,
self.scroll,
) else {
return false;
};
let target = scrollbar::scroll_for_y(metrics, y);
let moved = target != self.scroll;
self.scroll = target;
moved
}
pub fn hit_at(&self, y: u16) -> Option<ProblemHit> {
if self.visible_rows == 0 || y < self.first_row_y {
return None;
}
let offset = (y - self.first_row_y) as usize;
if offset >= self.visible_rows as usize {
return None;
}
match self.rows.get(self.scroll + offset)? {
RenderRow::Header(g) => {
let group = self.groups.get(*g)?;
Some(ProblemHit::Header(group.path.clone()))
}
RenderRow::Diag(g, i) => {
let group = self.groups.get(*g)?;
let item = group.items.get(*i)?;
Some(ProblemHit::Diagnostic {
path: group.path.clone(),
line: item.line,
col: item.col,
col_utf16: item.col_utf16,
})
}
}
}
pub fn diagnostic_at(&self, y: u16) -> Option<(PathBuf, ProblemItem)> {
if self.visible_rows == 0 || y < self.first_row_y {
return None;
}
let offset = (y - self.first_row_y) as usize;
if offset >= self.visible_rows as usize {
return None;
}
match self.rows.get(self.scroll + offset)? {
RenderRow::Header(_) => None,
RenderRow::Diag(g, i) => {
let group = self.groups.get(*g)?;
let item = group.items.get(*i)?;
Some((group.path.clone(), item.clone()))
}
}
}
fn build_rows(&mut self) {
self.rows.clear();
for (g, items) in self.visible_groups() {
if !self.group_by_file {
self.rows
.extend(items.into_iter().map(|i| RenderRow::Diag(g, i)));
continue;
}
self.rows.push(RenderRow::Header(g));
if !self.collapsed.contains(&self.groups[g].path) {
self.rows
.extend(items.into_iter().map(|i| RenderRow::Diag(g, i)));
}
}
}
fn cycle_filter(&mut self) {
self.filter = self.filter.next();
self.scroll = self.scroll.min(self.max_scroll());
}
fn toggle_group_by_file(&mut self) {
self.group_by_file = !self.group_by_file;
self.scroll = self.scroll.min(self.max_scroll());
}
pub fn click(&mut self, x: u16, y: u16) -> bool {
if rect_has(self.filter_rect, x, y) {
self.cycle_filter();
return true;
}
if rect_has(self.group_rect, x, y) {
self.toggle_group_by_file();
return true;
}
false
}
}
fn rect_has(r: Rect, x: u16, y: u16) -> bool {
x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}
impl Default for ProblemsPanel {
fn default() -> Self {
Self::new()
}
}
pub fn fix_prompt(item: &ProblemItem, rel_path: &str, hints: &[String]) -> String {
let kind = match item.severity {
DiagnosticSeverity::Error => "error",
DiagnosticSeverity::Warning => "warning",
DiagnosticSeverity::Information | DiagnosticSeverity::Hint => "diagnostic",
};
let source = if item.source.is_empty() {
String::from("a diagnostic tool")
} else {
item.source.clone()
};
let rule = item
.code
.as_ref()
.map(|c| format!(" (rule {})", c.value))
.unwrap_or_default();
let mut text = format!(
"Fix the {kind} reported by {source}{rule} at {rel_path}:{}:{}: {}",
item.line + 1,
item.col + 1,
item.message.trim().replace('\n', " ")
);
if !hints.is_empty() {
text.push_str("\nThe server offers these quick fixes; apply one if it is the right fix: ");
text.push_str(&hints.join("; "));
}
text.push_str(
"\nEdit the buffer with the smallest change that resolves the diagnostic and \
keeps the code's behaviour. If it cannot be fixed safely, say why in a note \
instead of editing.",
);
text
}
fn severity_glyph(severity: DiagnosticSeverity, theme: crate::theme::Theme) -> (char, Color) {
match severity {
DiagnosticSeverity::Error => (GLYPH_ERROR, theme.ui(COLOR_ERROR)),
DiagnosticSeverity::Warning => (GLYPH_WARNING, theme.ui(COLOR_WARNING)),
DiagnosticSeverity::Information | DiagnosticSeverity::Hint => {
(GLYPH_INFO, theme.ui(COLOR_INFO))
}
}
}
impl Widget for &mut ProblemsPanel {
fn render(self, area: Rect, buf: &mut Buffer) {
self.last_area = area;
self.last_scrollbar = Rect::default();
self.filter_rect = Rect::default();
self.group_rect = Rect::default();
self.visible_rows = 0;
self.build_rows();
if area.width == 0 || area.height == 0 {
return;
}
buf.set_style(area, Style::default().bg(self.theme.editor_bg()));
if self.groups.is_empty() {
let empty_msg = match self.scope {
ProblemScope::WholeProject => "No problems have been detected in the workspace.",
ProblemScope::OpenFiles => {
"No problems in the open files. Switch scope to Whole Project to see the rest."
}
};
Paragraph::new(Line::from(Span::styled(
empty_msg,
Style::default().fg(self.theme.ui(COLOR_DIM)),
)))
.render(
Rect {
x: area.x + 1,
y: area.y,
width: area.width.saturating_sub(1),
height: 1,
},
buf,
);
return;
}
let toolbar = Rect {
x: area.x,
y: area.y,
width: area.width,
height: 1,
};
self.render_toolbar(toolbar, buf);
let body = Rect {
x: area.x,
y: area.y + 1,
width: area.width,
height: area.height.saturating_sub(1),
};
if body.height == 0 {
return;
}
if self.rows.is_empty() {
Paragraph::new(Line::from(Span::styled(
"No problems match the current filter.",
Style::default().fg(self.theme.ui(COLOR_DIM)),
)))
.render(
Rect {
x: body.x + 1,
y: body.y,
width: body.width.saturating_sub(1),
height: 1,
},
buf,
);
return;
}
self.first_row_y = body.y;
self.viewport_rows = body.height;
let total = self.total_rows();
self.scroll = self.scroll.min(total.saturating_sub(body.height as usize));
let bar = scrollbar::vertical_metrics(
Rect {
x: body.x + body.width.saturating_sub(1),
y: body.y,
width: 1,
height: body.height,
},
total,
body.height as usize,
self.scroll,
);
let content_w = body.width.saturating_sub(u16::from(bar.is_some()));
let visible = (body.height as usize).min(self.rows.len().saturating_sub(self.scroll));
self.visible_rows = visible as u16;
for row in 0..visible {
let render_row = self.rows[self.scroll + row].clone();
let y = body.y + row as u16;
let row_rect = Rect {
x: body.x,
y,
width: content_w,
height: 1,
};
if let Some(bg) =
crate::widgets::hover::row_hover_bg(row_rect, self.hover_pointer, self.theme)
{
buf.set_style(row_rect, Style::default().bg(bg));
}
let spans = match render_row {
RenderRow::Header(g) => self.header_spans(g),
RenderRow::Diag(g, i) => self.diag_spans(g, i),
};
Paragraph::new(Line::from(spans)).render(row_rect, buf);
}
if let Some(metrics) = bar {
self.last_scrollbar = metrics.area;
scrollbar::render_vertical(buf, metrics, self.focused, self.theme);
}
}
}
impl ProblemsPanel {
fn render_toolbar(&mut self, area: Rect, buf: &mut Buffer) {
let muted = self.theme.ignored_fg();
let accent = self.theme.accent();
let chip = self.theme.accent_chip_bg();
let shown_filter: String = {
let n = self.text_filter.chars().count();
self.text_filter
.chars()
.skip(n.saturating_sub(FILTER_CHIP_CHARS))
.collect()
};
let filter_label = if self.text_filter.is_empty() {
format!(" {} \u{25be} ", self.filter.label())
} else {
format!(
" {} \u{25be} \u{eb85} {} ",
self.filter.label(),
shown_filter
)
};
let group_label = format!(
" {} ",
if self.group_by_file {
"Grouped"
} else {
"Flat"
}
);
let fw = filter_label.chars().count() as u16;
let gw = group_label.chars().count() as u16;
let total = fw + 1 + gw + 1;
let mut x = area.x + area.width.saturating_sub(total.min(area.width));
let mut control = |label: String, active: bool, buf: &mut Buffer| -> Rect {
let w = (label.chars().count() as u16).min(area.right().saturating_sub(x));
let r = Rect {
x,
y: area.y,
width: w,
height: 1,
};
let style = if active {
Style::default().fg(accent).bg(chip)
} else {
Style::default().fg(muted)
};
Paragraph::new(Line::from(Span::styled(label, style))).render(r, buf);
x += w + 1;
r
};
self.filter_rect = control(
filter_label,
self.filter != ProblemFilter::All || !self.text_filter.is_empty(),
buf,
);
self.group_rect = control(group_label, !self.group_by_file, buf);
}
fn header_spans(&self, g: usize) -> Vec<Span<'static>> {
let group = &self.groups[g];
let chevron = if self.collapsed.contains(&group.path) {
crate::icons::CHEVRON_CLOSED
} else {
crate::icons::CHEVRON_OPEN
};
let suffix = group
.name
.rfind('.')
.map(|i| group.name[i..].to_string())
.unwrap_or_default();
let icon = crate::icons::for_path(&group.name, &suffix);
let mut spans = vec![
Span::styled(
format!("{chevron} "),
Style::default().fg(self.theme.ui(COLOR_DIM)),
),
Span::styled(
format!("{} ", icon.glyph),
Style::default().fg(self.theme.ui(icon.color)),
),
Span::styled(
group.name.clone(),
Style::default()
.fg(self.theme.ui(COLOR_HEADER))
.add_modifier(Modifier::BOLD),
),
];
if !group.rel_dir.is_empty() {
spans.push(Span::styled(
format!(" {}", group.rel_dir),
Style::default().fg(self.theme.ui(COLOR_DIM)),
));
}
let shown = group
.items
.iter()
.filter(|it| self.keeps_item(group, it))
.count();
spans.push(Span::styled(
format!(" {shown}"),
Style::default().fg(self.theme.ui(COLOR_DIM)),
));
spans
}
fn diag_spans(&self, g: usize, i: usize) -> Vec<Span<'static>> {
let item = &self.groups[g].items[i];
let (glyph, color) = severity_glyph(item.severity, self.theme);
let message = item.message.replace('\n', " ");
let fixing = self
.fixing
.as_ref()
.is_some_and(|(path, line)| *path == self.groups[g].path && *line == item.line);
let lead = if fixing && !self.fix_glyph.is_empty() {
Span::styled(
format!(" {} ", self.fix_glyph),
Style::default().fg(self.theme.ui(COLOR_INFO)),
)
} else {
Span::styled(format!(" {glyph} "), Style::default().fg(color))
};
let mut spans = vec![
lead,
Span::styled(message, Style::default().fg(self.theme.ui(COLOR_MSG))),
];
let source = match &item.code {
Some(code) => code.label(&item.source),
None => item.source.clone(),
};
if !source.is_empty() {
spans.push(Span::styled(
format!(" {source} "),
Style::default().fg(self.theme.ui(COLOR_DIM)),
));
}
spans.push(Span::styled(
format!("[Ln {}, Col {}]", item.line + 1, item.col + 1),
Style::default().fg(self.theme.ui(COLOR_DIM)),
));
if !self.group_by_file {
spans.push(Span::styled(
format!(" {}", self.groups[g].name),
Style::default().fg(self.theme.ui(COLOR_DIM)),
));
}
spans
}
}
#[cfg(test)]
mod tests {
use super::*;
fn diag(line: u32, severity: DiagnosticSeverity, msg: &str) -> ProblemItem {
ProblemItem {
line,
col: 0,
col_utf16: false,
severity,
message: msg.to_string(),
source: "rustc".to_string(),
code: None,
}
}
fn group(name: &str, items: Vec<ProblemItem>) -> ProblemGroup {
ProblemGroup {
path: PathBuf::from(format!("/repo/src/{name}")),
name: name.to_string(),
rel_dir: "src".to_string(),
items,
}
}
fn render(p: &mut ProblemsPanel, w: u16, h: u16) -> String {
let area = Rect {
x: 0,
y: 0,
width: w,
height: h,
};
let mut buf = Buffer::empty(area);
p.render(area, &mut buf);
let mut out = String::new();
for y in 0..h {
for x in 0..w {
out.push_str(buf[(x, y)].symbol());
}
out.push('\n');
}
out
}
#[test]
fn the_top_diagnostic_follows_the_scroll_filters_and_folds() {
use DiagnosticSeverity::{Error, Warning};
let mut p = ProblemsPanel::new();
assert!(p.top_diagnostic().is_none(), "no problems, no top row");
p.set_groups(vec![
group("a.rs", vec![diag(1, Warning, "w1"), diag(2, Error, "e1")]),
group("b.rs", vec![diag(5, Error, "e2")]),
]);
let top = |p: &ProblemsPanel| {
p.top_diagnostic()
.map(|(g, it)| (g.name.clone(), it.message.clone()))
};
assert_eq!(top(&p), Some(("a.rs".into(), "w1".into())));
p.scroll_down(2);
assert_eq!(top(&p), Some(("a.rs".into(), "e1".into())));
p.scroll_down(1);
assert_eq!(top(&p), Some(("b.rs".into(), "e2".into())));
p.scroll_up(10);
p.cycle_filter();
assert_eq!(top(&p), Some(("a.rs".into(), "e1".into())));
p.cycle_filter();
p.cycle_filter();
p.toggle_collapse(&PathBuf::from("/repo/src/a.rs"));
assert_eq!(top(&p), Some(("b.rs".into(), "e2".into())));
}
#[test]
fn a_long_or_wide_filter_keeps_the_toolbar_inside_the_panel() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
for c in "\u{5e83}\u{3044}\u{6587}\u{5b57}".repeat(20).chars() {
p.push_filter_char(c);
}
let area = Rect {
x: 0,
y: 0,
width: 60,
height: 6,
};
let mut buf = Buffer::empty(area);
(&mut p).render(area, &mut buf);
let row: String = (0..area.width)
.map(|x| buf[(x, 0)].symbol().to_string())
.collect();
assert!(
row.contains("All"),
"the severity control must survive a long filter, got {row:?}"
);
assert!(
p.text_filter.chars().count() > FILTER_CHIP_CHARS,
"the filter itself stays unbounded; only its display is capped"
);
}
#[test]
fn text_filter_narrows_by_message_and_path() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"alpha.rs",
vec![
diag(0, DiagnosticSeverity::Error, "Mismatched types"),
diag(1, DiagnosticSeverity::Warning, "unused variable"),
],
),
group("beta.rs", vec![diag(0, DiagnosticSeverity::Error, "boom")]),
]);
assert_eq!(p.total_rows(), 5, "2 headers + 3 diagnostics");
for c in "MISMATCH".chars() {
p.push_filter_char(c.to_ascii_lowercase());
}
assert_eq!(p.total_rows(), 2, "one header + the one matching row");
while !p.text_filter.is_empty() {
p.pop_filter_char();
}
assert_eq!(p.total_rows(), 5);
for c in "beta".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2);
while !p.text_filter.is_empty() {
p.pop_filter_char();
}
for c in "unused".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "the warning matches on its own");
while p.filter != ProblemFilter::Errors {
p.cycle_filter();
}
assert_eq!(p.total_rows(), 0, "text and severity filters compose");
assert!(p.clear_text_filter(), "clearing reports it had text");
assert!(!p.clear_text_filter(), "second clear is a no-op");
}
#[test]
fn text_filter_matches_the_displayed_rule_code() {
let mut coded = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
coded.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: Some(String::from("Ruff")),
href: None,
});
let plain = diag(1, DiagnosticSeverity::Warning, "unused variable");
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("app.py", vec![coded, plain])]);
for c in "f401".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "one header + the coded row");
p.clear_text_filter();
for c in "ruff(".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 2, "the source(code) label matches");
p.clear_text_filter();
for c in "rustc".chars() {
p.push_filter_char(c);
}
assert_eq!(p.total_rows(), 0, "no row shows `rustc`");
}
#[test]
fn the_header_count_follows_the_severity_filter() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh1"),
diag(2, DiagnosticSeverity::Warning, "meh2"),
],
)]);
while p.filter != ProblemFilter::Errors {
p.cycle_filter();
}
let text: String = p
.header_spans(0)
.iter()
.map(|s| s.content.clone())
.collect();
assert!(
text.ends_with(" 1"),
"the badge must count only diagnostics passing the filter, got {text:?}"
);
}
#[test]
fn counts_aggregate_across_files() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh"),
],
),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
assert_eq!(p.total_count(), 3);
assert_eq!(p.error_count(), 2);
assert_eq!(p.warning_count(), 1);
}
#[test]
fn header_then_diag_rows_map_to_hits() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![
diag(4, DiagnosticSeverity::Error, "boom"),
diag(9, DiagnosticSeverity::Warning, "meh"),
],
)]);
render(&mut p, 60, 6);
assert_eq!(p.hit_at(0), None, "row 0 is the toolbar, not a list row");
assert_eq!(
p.hit_at(1),
Some(ProblemHit::Header(PathBuf::from("/repo/src/a.rs"))),
"row 1 is the file header",
);
assert_eq!(
p.hit_at(2),
Some(ProblemHit::Diagnostic {
path: PathBuf::from("/repo/src/a.rs"),
line: 4,
col: 0,
col_utf16: false,
}),
);
assert_eq!(
p.hit_at(3),
Some(ProblemHit::Diagnostic {
path: PathBuf::from("/repo/src/a.rs"),
line: 9,
col: 0,
col_utf16: false,
}),
);
assert_eq!(p.hit_at(4), None, "below the last row");
}
#[test]
fn hit_carries_the_column_unit_of_each_source() {
let mut lsp_item = diag(4, DiagnosticSeverity::Error, "from a server");
lsp_item.col = 7;
lsp_item.col_utf16 = true;
let mut build_item = diag(9, DiagnosticSeverity::Error, "from cargo");
build_item.col = 7;
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("a.rs", vec![lsp_item, build_item])]);
render(&mut p, 60, 6);
let utf16_of = |hit| match hit {
Some(ProblemHit::Diagnostic { col_utf16, .. }) => Some(col_utf16),
_ => None,
};
assert_eq!(
utf16_of(p.hit_at(2)),
Some(true),
"the server's diagnostic keeps its UTF-16 column"
);
assert_eq!(
utf16_of(p.hit_at(3)),
Some(false),
"the build tool's identical column is NOT UTF-16"
);
}
#[test]
fn a_row_shows_the_rule_code_after_the_message() {
let code = |source: Option<&str>| crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: source.map(String::from),
href: Some(String::from(
"https://docs.astral.sh/ruff/rules/unused-import",
)),
};
let mut named = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
named.source = String::from("ruff");
named.code = Some(code(Some("Ruff")));
let mut unnamed = diag(1, DiagnosticSeverity::Error, "bad argument");
unnamed.source = String::from("ty");
unnamed.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("invalid-argument-type"),
source: None,
href: None,
});
let plain = diag(2, DiagnosticSeverity::Error, "no code here");
let mut p = ProblemsPanel::new();
p.set_groups(vec![group("app.py", vec![named, unnamed, plain])]);
let screen = render(&mut p, 120, 8);
assert!(
screen.contains("`os` imported but unused Ruff(F401) [Ln 1"),
"{screen}"
);
assert!(
screen.contains("bad argument ty(invalid-argument-type) [Ln 2"),
"{screen}"
);
assert!(screen.contains("no code here rustc [Ln 3"), "{screen}");
assert!(!screen.contains("rustc("), "{screen}");
}
#[test]
fn the_fix_prompt_names_the_rule() {
let mut item = diag(0, DiagnosticSeverity::Warning, "`os` imported but unused");
item.source = String::from("ruff");
assert!(!fix_prompt(&item, "app.py", &[]).contains("rule"));
item.code = Some(crate::lsp::manager::DiagnosticCode {
value: String::from("F401"),
source: Some(String::from("Ruff")),
href: None,
});
assert!(
fix_prompt(&item, "app.py", &[])
.starts_with("Fix the warning reported by ruff (rule F401) at app.py:1:1")
);
}
#[test]
fn collapse_hides_diagnostic_rows() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
let path = PathBuf::from("/repo/src/a.rs");
render(&mut p, 60, 6);
assert_eq!(p.total_rows(), 2, "header + one diagnostic");
p.toggle_collapse(&path);
render(&mut p, 60, 6);
assert_eq!(p.total_rows(), 1, "collapsed: header only");
assert_eq!(p.hit_at(2), None, "no diagnostic row when collapsed");
assert_eq!(p.hit_at(1), Some(ProblemHit::Header(path)));
}
#[test]
fn the_empty_state_names_the_scope_it_actually_searched() {
let mut p = ProblemsPanel::new();
p.scope = ProblemScope::OpenFiles;
let text = render(&mut p, 90, 6);
assert!(
text.contains("open files"),
"scoped empty state must say so: {text:?}"
);
assert!(
!text.contains("in the workspace"),
"and must not claim the workspace is clean: {text:?}"
);
p.scope = ProblemScope::WholeProject;
let text = render(&mut p, 90, 6);
assert!(text.contains("workspace"), "unscoped keeps its wording");
}
#[test]
fn empty_shows_no_problems_message() {
let mut p = ProblemsPanel::new();
let text = render(&mut p, 60, 3);
assert!(text.contains("No problems"), "empty state: {text:?}");
}
#[test]
fn severity_glyphs_are_the_verified_codicons() {
assert_eq!(
severity_glyph(DiagnosticSeverity::Error, crate::theme::Theme::default()).0,
'\u{ea87}'
);
assert_eq!(
severity_glyph(DiagnosticSeverity::Warning, crate::theme::Theme::default()).0,
'\u{ea6c}'
);
assert_eq!(
severity_glyph(
DiagnosticSeverity::Information,
crate::theme::Theme::default()
)
.0,
'\u{ea74}'
);
assert_eq!(
severity_glyph(DiagnosticSeverity::Hint, crate::theme::Theme::default()).0,
'\u{ea74}'
);
}
#[test]
fn severity_filter_hides_lower_severities_and_empty_groups() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group(
"a.rs",
vec![
diag(0, DiagnosticSeverity::Error, "boom"),
diag(1, DiagnosticSeverity::Warning, "meh"),
],
),
group(
"b.rs",
vec![diag(2, DiagnosticSeverity::Warning, "only warn")],
),
]);
assert_eq!(p.total_rows(), 5);
p.cycle_filter();
assert_eq!(p.filter, ProblemFilter::Errors);
assert_eq!(p.total_rows(), 2);
assert_eq!(p.total_count(), 3);
assert_eq!(p.error_count(), 1);
}
#[test]
fn group_by_file_toggle_flattens_to_diagnostics_only() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![
group("a.rs", vec![diag(0, DiagnosticSeverity::Error, "boom")]),
group("b.rs", vec![diag(2, DiagnosticSeverity::Error, "kaboom")]),
]);
assert_eq!(p.total_rows(), 4);
p.toggle_group_by_file();
assert!(!p.group_by_file);
assert_eq!(p.total_rows(), 2);
render(&mut p, 80, 6);
assert!(matches!(p.hit_at(1), Some(ProblemHit::Diagnostic { .. })));
}
#[test]
fn active_toolbar_control_gets_the_accent_chip_default_is_plain() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
let area = Rect {
x: 0,
y: 0,
width: 80,
height: 6,
};
let mut buf = Buffer::empty(area);
p.render(area, &mut buf);
let chip = p.theme.accent_chip_bg();
let cell_bg = |b: &Buffer, r: Rect| b[(r.x, r.y)].style().bg;
assert_ne!(
cell_bg(&buf, p.filter_rect),
Some(chip),
"All filter is plain, no chip",
);
p.cycle_filter();
let mut buf = Buffer::empty(area);
p.render(area, &mut buf);
assert_eq!(
cell_bg(&buf, p.filter_rect),
Some(chip),
"a non-default filter is chipped with the theme accent",
);
assert_ne!(
cell_bg(&buf, p.group_rect),
Some(chip),
"grouping is still default, so its control stays plain",
);
}
#[test]
fn toolbar_click_cycles_filter_then_toggles_grouping() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(0, DiagnosticSeverity::Error, "boom")],
)]);
render(&mut p, 80, 6);
let fr = p.filter_rect;
assert!(fr.width > 0, "filter button rect recorded");
assert!(p.click(fr.x, fr.y), "filter button consumes the click");
assert_eq!(p.filter, ProblemFilter::Errors);
let gr = p.group_rect;
assert!(p.click(gr.x, gr.y), "group button consumes the click");
assert!(!p.group_by_file);
assert!(!p.click(0, 5));
}
#[test]
fn diag_row_shows_message_and_one_based_position() {
let mut p = ProblemsPanel::new();
p.set_groups(vec![group(
"a.rs",
vec![diag(
4,
DiagnosticSeverity::Error,
"function `run` is never used",
)],
)]);
let text = render(&mut p, 80, 4);
assert!(text.contains("function `run` is never used"), "{text:?}");
assert!(text.contains("Ln 5"), "one-based line: {text:?}");
}
#[test]
fn fix_prompt_names_the_diagnostic_and_carries_the_servers_hints() {
let mut item = diag(
6,
DiagnosticSeverity::Error,
"unused import: `std::io`\nremove it",
);
item.col = 4;
let text = fix_prompt(&item, "src/lib.rs", &[]);
assert!(
text.starts_with("Fix the error reported by rustc at src/lib.rs:7:5: unused import")
);
assert!(
text.contains("unused import: `std::io` remove it"),
"a multi-line message collapses to one line: {text}"
);
assert!(!text.contains("quick fixes"), "no hints, no hint line");
assert!(text.contains("smallest change"));
let hinted = fix_prompt(
&item,
"src/lib.rs",
&[
String::from("Remove unused import"),
String::from("Fix all"),
],
);
assert!(hinted.contains("quick fixes"));
assert!(hinted.contains("Remove unused import; Fix all"));
item.source.clear();
item.severity = DiagnosticSeverity::Hint;
let anon = fix_prompt(&item, "a.py", &[]);
assert!(anon.starts_with("Fix the diagnostic reported by a diagnostic tool at a.py:7:5"));
}
#[test]
fn the_row_being_fixed_wears_the_spinner() {
let mut p = ProblemsPanel::new();
let path = PathBuf::from("/w/src/a.rs");
p.set_groups(vec![ProblemGroup {
path: path.clone(),
name: "a.rs".into(),
rel_dir: "src".into(),
items: vec![
diag(3, DiagnosticSeverity::Error, "first"),
diag(9, DiagnosticSeverity::Error, "second"),
],
}]);
let before = render(&mut p, 60, 6);
assert!(
!before.contains('\u{25DC}'),
"no spinner while nothing is being fixed"
);
p.fixing = Some((path.clone(), 9));
p.fix_glyph = "\u{25DC}";
let out = render(&mut p, 60, 6);
let rows: Vec<&str> = out.lines().collect();
let first = rows.iter().find(|r| r.contains("first")).unwrap();
let second = rows.iter().find(|r| r.contains("second")).unwrap();
assert!(
!first.contains('\u{25DC}'),
"the other row keeps its glyph: {first}"
);
assert!(
second.contains('\u{25DC}'),
"the fixing row shows the spinner: {second}"
);
assert!(
!second.contains(GLYPH_ERROR),
"in place of its severity glyph: {second}"
);
assert_eq!(
p.diagnostic_at(2).map(|(pth, item)| (pth, item.line)),
Some((path, 3)),
"the row under the pointer resolves to its whole diagnostic"
);
}
}