use std::path::PathBuf;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph, Widget},
};
use crate::icons::for_outline_kind;
use crate::lsp::manager::OutlineSymbol;
use crate::widgets::file_finder::fuzzy_score;
use crate::widgets::picker_colours;
use crate::widgets::picker_query;
pub struct SymbolPicker {
pub query: String,
pub cursor: usize,
pub path: PathBuf,
symbols: Vec<OutlineSymbol>,
pub results: Vec<usize>,
pub selected: usize,
pub scroll: usize,
pub last_inner_height: u16,
pub last_rect: Rect,
}
impl SymbolPicker {
pub fn new(path: PathBuf, symbols: Vec<OutlineSymbol>) -> Self {
let mut me = Self {
query: String::new(),
cursor: 0,
path,
symbols,
results: Vec::new(),
selected: 0,
scroll: 0,
last_inner_height: 0,
last_rect: Rect::default(),
};
me.refresh_results();
me
}
pub fn is_line_mode(&self) -> bool {
self.query.trim_start().starts_with(':')
}
pub fn line_target(&self) -> Option<usize> {
self.query
.trim_start()
.strip_prefix(':')
.map(str::trim)
.filter(|s| !s.is_empty())
.and_then(|s| s.parse::<usize>().ok())
.filter(|&n| n >= 1)
}
pub fn selected_name(&self) -> Option<&str> {
let idx = *self.results.get(self.selected)?;
self.symbols.get(idx).map(|s| s.name.as_str())
}
pub fn selected_target(&self) -> Option<(u32, u32)> {
let idx = *self.results.get(self.selected)?;
let sym = self.symbols.get(idx)?;
Some((sym.line, sym.character))
}
pub fn push_char(&mut self, c: char) {
picker_query::insert(&mut self.query, &mut self.cursor, c);
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn pop_char(&mut self) {
if !picker_query::backspace(&mut self.query, &mut self.cursor) {
return;
}
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn delete_char(&mut self) {
if !picker_query::delete(&mut self.query, self.cursor) {
return;
}
self.refresh_results();
self.selected = 0;
self.scroll = 0;
}
pub fn move_cursor_left(&mut self) {
picker_query::left(&mut self.cursor);
}
pub fn move_cursor_right(&mut self) {
picker_query::right(&self.query, &mut self.cursor);
}
pub fn move_cursor_home(&mut self) {
self.cursor = 0;
}
pub fn move_cursor_end(&mut self) {
picker_query::end(&self.query, &mut self.cursor);
}
pub fn select_next(&mut self) {
if self.results.is_empty() {
return;
}
if self.selected + 1 < self.results.len() {
self.selected += 1;
}
}
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
pub fn row_index_at(&self, y: u16) -> Option<usize> {
if self.is_line_mode() {
return None;
}
let list_top = self.last_rect.y.saturating_add(3);
if y < list_top || y - list_top >= self.last_inner_height {
return None;
}
let idx = self.scroll + (y - list_top) as usize;
(idx < self.results.len()).then_some(idx)
}
fn refresh_results(&mut self) {
if self.is_line_mode() {
self.results = (0..self.symbols.len()).collect();
return;
}
let needle = self.query.trim().to_lowercase();
if needle.is_empty() {
self.results = (0..self.symbols.len()).collect();
return;
}
let mut scored: Vec<(i32, usize)> = self
.symbols
.iter()
.enumerate()
.filter_map(|(idx, sym)| {
fuzzy_score(&needle, &sym.name.to_lowercase(), 0).map(|score| (score, idx))
})
.collect();
scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
self.results = scored.into_iter().map(|(_, idx)| idx).collect();
}
}
pub fn render_symbol_picker(
picker: &mut SymbolPicker,
area: Rect,
buf: &mut Buffer,
theme: crate::theme::Theme,
center: bool,
) {
let width = area.width.saturating_mul(7) / 10;
let width = width.clamp(40, 100).min(area.width);
let height = area.height.saturating_mul(6) / 10;
let height = height.max(10).min(area.height);
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = if center {
area.y + (area.height.saturating_sub(height)) / 2
} else {
area.y + (area.height.saturating_sub(height)) / 4
};
let rect = Rect {
x,
y,
width,
height,
};
picker.last_rect = rect;
Widget::render(Clear, rect, buf);
let title = Span::styled(
" Go to Symbol — Esc to close, ↑/↓ to navigate, Enter to go, : for line ",
Style::default()
.fg(theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
.add_modifier(Modifier::BOLD),
);
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(theme.ui(picker_colours::BORDER)))
.title(title.clone())
.style(Style::default().bg(theme.ui(picker_colours::BODY)));
let inner = Rect {
x: rect.x + 1,
y: rect.y + 1,
width: rect.width.saturating_sub(2),
height: rect.height.saturating_sub(2),
};
Widget::render(block, rect, buf);
if theme.framed_overlays() {
crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
}
let sel_bg = if theme.gradient() {
let (r, g, b) = crate::gradient::POPUP_SEL_BG;
Color::Rgb(r, g, b)
} else {
theme.ui(picker_colours::SELECTION)
};
let tones = crate::theme::tones(theme);
if inner.height == 0 || inner.width == 0 {
return;
}
let query_style = Style::default()
.fg(theme.ui(picker_colours::TEXT))
.add_modifier(Modifier::BOLD);
let caret_style = Style::default()
.fg(theme.ui(picker_colours::BODY))
.bg(theme.ui(picker_colours::TEXT))
.add_modifier(Modifier::SLOW_BLINK);
let cursor = picker.cursor.min(picker.query.chars().count());
let before: String = picker.query.chars().take(cursor).collect();
let at: String = picker.query.chars().skip(cursor).take(1).collect();
let after: String = picker.query.chars().skip(cursor + 1).collect();
let caret_glyph = if at.is_empty() { String::from(" ") } else { at };
let prompt_line = Line::from(vec![
Span::styled("@ ", Style::default().fg(theme.ui(picker_colours::PROMPT))),
Span::styled(before, query_style),
Span::styled(caret_glyph, caret_style),
Span::styled(after, query_style),
]);
Widget::render(
Paragraph::new(prompt_line),
Rect {
x: inner.x,
y: inner.y,
width: inner.width,
height: 1,
},
buf,
);
let sep_line = Line::from(Span::styled(
"─".repeat(inner.width as usize),
Style::default().fg(theme.ui(Color::Rgb(0x3b, 0x42, 0x52))),
));
Widget::render(
Paragraph::new(sep_line),
Rect {
x: inner.x,
y: inner.y + 1,
width: inner.width,
height: 1,
},
buf,
);
let list_rect = Rect {
x: inner.x,
y: inner.y + 2,
width: inner.width,
height: inner.height.saturating_sub(2),
};
picker.last_inner_height = list_rect.height;
if list_rect.height == 0 {
return;
}
if picker.is_line_mode() {
let msg = match picker.line_target() {
Some(n) => format!(" Go to line {n}"),
None => String::from(" Type a line number, e.g. :42"),
};
Widget::render(
Paragraph::new(Line::from(Span::styled(
msg,
Style::default().fg(theme.ui(picker_colours::DETAIL_BRIGHT)),
))),
list_rect,
buf,
);
return;
}
let visible = list_rect.height as usize;
let total = picker.results.len();
if picker.selected >= picker.scroll + visible {
picker.scroll = picker.selected + 1 - visible;
}
if picker.selected < picker.scroll {
picker.scroll = picker.selected;
}
let end = (picker.scroll + visible).min(total);
if total == 0 {
let empty = Line::from(Span::styled(
String::from(" No symbols in this file"),
Style::default().fg(theme.ui(picker_colours::DIM)),
));
Widget::render(Paragraph::new(empty), list_rect, buf);
return;
}
let mut lines: Vec<Line<'static>> = Vec::with_capacity(end - picker.scroll);
for (offset, &sym_idx) in picker.results[picker.scroll..end].iter().enumerate() {
let row_idx = picker.scroll + offset;
let is_selected = row_idx == picker.selected;
let Some(sym) = picker.symbols.get(sym_idx) else {
continue;
};
let icon = for_outline_kind(sym.kind);
let (row_style, detail_style, icon_style) = match tones {
Some(t) => (
Style::default().fg(if is_selected { t.strong() } else { t.text() }),
Style::default().fg(t.muted()),
Style::default().fg(theme.ui(icon.color)),
),
None if is_selected => (
Style::default().bg(sel_bg).fg(theme.ui(Color::White)),
Style::default()
.bg(sel_bg)
.fg(theme.ui(picker_colours::DETAIL_BRIGHT)),
Style::default().bg(sel_bg).fg(theme.ui(icon.color)),
),
None => (
Style::default().fg(theme.ui(picker_colours::TEXT)),
Style::default().fg(theme.ui(picker_colours::DETAIL)),
Style::default().fg(theme.ui(icon.color)),
),
};
let indent = " ".repeat((sym.depth as usize).min(6));
let prefix = if is_selected && tones.is_none() {
"> "
} else {
" "
};
let line_label = format!("{} ", sym.line + 1);
let used = prefix.chars().count()
+ indent.chars().count()
+ 2 + sym.name.chars().count()
+ line_label.chars().count();
let pad = (list_rect.width as usize).saturating_sub(used).max(1);
lines.push(Line::from(vec![
Span::styled(prefix.to_string(), row_style),
Span::styled(indent, row_style),
Span::styled(format!("{} ", icon.glyph), icon_style),
Span::styled(sym.name.clone(), row_style),
Span::styled(" ".repeat(pad), row_style),
Span::styled(line_label, detail_style),
]));
}
Widget::render(Paragraph::new(lines), list_rect, buf);
if let Some(t) = tones {
paint_selected(buf, rect, list_rect, picker.selected, picker.scroll, t);
}
}
pub(crate) fn paint_selected(
buf: &mut Buffer,
card: Rect,
list: Rect,
selected: usize,
scroll: usize,
t: crate::theme::Tones,
) {
let Some(row) = selected.checked_sub(scroll) else {
return;
};
if row >= usize::from(list.height) {
return;
}
let band = Rect::new(card.x, list.y + row as u16, card.width.saturating_sub(1), 1);
crate::widgets::surface::paint_selected_row(buf, band, t, t.raised, true);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lsp::manager::OutlineKind;
fn sym(name: &str, kind: OutlineKind, depth: u16, line: u32) -> OutlineSymbol {
OutlineSymbol {
name: name.to_string(),
detail: None,
kind,
depth,
line,
character: 0,
range_start_line: line,
range_end_line: line,
range_start_character: 0,
range_end_character: u32::MAX,
}
}
fn picker() -> SymbolPicker {
SymbolPicker::new(
PathBuf::from("f.rs"),
vec![
sym("alpha", OutlineKind::Function, 0, 1),
sym("beta", OutlineKind::Method, 1, 5),
sym("gamma_helper", OutlineKind::Function, 0, 20),
],
)
}
#[test]
fn empty_query_lists_every_symbol_in_order() {
let p = picker();
assert_eq!(p.results, vec![0, 1, 2]);
}
#[test]
fn row_index_at_refuses_clicks_in_line_mode() {
let mut p = picker();
p.last_rect = Rect {
x: 10,
y: 5,
width: 60,
height: 10,
};
p.last_inner_height = 6;
assert_eq!(
p.row_index_at(8),
Some(0),
"outside line mode the first list row maps to the first symbol"
);
for c in [':', '4', '2'] {
p.push_char(c);
}
assert!(p.is_line_mode());
assert_eq!(
p.row_index_at(8),
None,
"line mode renders a hint, not rows; clicks must map to nothing"
);
}
#[test]
fn fuzzy_query_filters_and_ranks() {
let mut p = picker();
p.push_char('g');
p.push_char('h');
assert_eq!(p.results, vec![2]);
assert_eq!(p.selected_target(), Some((20, 0)));
}
#[test]
fn line_mode_parses_the_target_line() {
let mut p = picker();
for c in ":42".chars() {
p.push_char(c);
}
assert!(p.is_line_mode());
assert_eq!(p.line_target(), Some(42));
}
#[test]
fn line_mode_with_no_digits_has_no_target() {
let mut p = picker();
p.push_char(':');
assert!(p.is_line_mode());
assert_eq!(p.line_target(), None);
}
#[test]
fn selected_target_follows_navigation() {
let mut p = picker();
p.select_next();
assert_eq!(p.selected_target(), Some((5, 0)));
p.select_prev();
assert_eq!(p.selected_target(), Some((1, 0)));
}
#[test]
fn croft_loch_selects_a_row_with_the_band_and_bar() {
use crate::widgets::surface;
let theme = crate::theme::Theme::from_id("loch");
let t = crate::theme::tones(theme).unwrap();
let mut p = picker();
p.select_next();
let area = Rect::new(0, 0, 100, 30);
let mut buf = Buffer::empty(area);
render_symbol_picker(&mut p, area, &mut buf, theme, true);
let r = p.last_rect;
let row = |y: u16| -> String { (r.x..r.right()).map(|x| buf[(x, y)].symbol()).collect() };
let list_top = r.y + 3;
let y = list_top + 1;
assert!(row(y).contains("beta"), "{}", row(y));
assert!(!row(y).contains("> "), "{}", row(y));
assert_eq!(buf[(r.x, y)].symbol(), surface::ROW_BAR);
assert_eq!(buf[(r.x, y)].fg, t.accent());
assert_eq!(buf[(r.x + 2, y)].bg, t.band());
let name_x = (r.x..r.right())
.find(|&x| buf[(x, y)].symbol() == "b")
.unwrap();
assert_eq!(buf[(name_x, y)].fg, t.strong());
assert_ne!(buf[(r.x, list_top)].symbol(), surface::ROW_BAR);
assert_eq!(buf[(r.x + 2, list_top)].bg, t.raised());
}
}