consciousness/src/user/widgets.rs

263 lines
9.3 KiB
Rust
Raw Normal View History

// widgets.rs — Shared TUI helpers and reusable components
use ratatui::{
layout::{Margin, Rect},
style::{Color, Modifier, Style},
text::Line,
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, Wrap},
Frame,
crossterm::event::KeyCode,
};
use crate::agent::context::ContextSection;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Standard pane block — cyan border, right-aligned title.
pub fn pane_block(title: &str) -> Block<'_> {
Block::default()
.title_top(Line::from(format!(" {} ", title)).right_aligned())
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Cyan))
}
/// Focused pane block — brighter border to indicate focus.
pub fn pane_block_focused(title: &str, focused: bool) -> Block<'_> {
let color = if focused { Color::White } else { Color::Cyan };
Block::default()
.title_top(Line::from(format!(" {} ", title)).right_aligned())
.borders(Borders::ALL)
.border_style(Style::default().fg(color))
}
/// Format a duration in seconds as a compact human-readable string.
pub fn format_age(secs: f64) -> String {
if secs < 60.0 { format!("{:.0}s", secs) }
else if secs < 3600.0 { format!("{:.0}m", secs / 60.0) }
else if secs < 86400.0 { format!("{:.1}h", secs / 3600.0) }
else { format!("{:.0}d", secs / 86400.0) }
}
/// Format a unix epoch timestamp as age from now.
pub fn format_ts_age(ts: i64) -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
format_age((now - ts).max(0) as f64)
}
/// Key legend for SectionTree panes.
pub fn tree_legend() -> Line<'static> {
Line::styled(
" ↑↓:nav →/Enter:expand ←:collapse e:expand all c:collapse all PgUp/Dn Home/End ",
Style::default().fg(Color::DarkGray),
)
}
/// Render a paragraph with a vertical scrollbar.
pub fn render_scrollable(
frame: &mut Frame,
area: Rect,
lines: Vec<Line<'_>>,
block: Block<'_>,
scroll: u16,
) {
let content_len = lines.len();
let para = Paragraph::new(lines)
.block(block)
.wrap(Wrap { trim: false })
.scroll((scroll, 0));
frame.render_widget(para, area);
let visible = area.height.saturating_sub(2) as usize;
if content_len > visible {
let mut sb_state = ScrollbarState::new(content_len)
.position(scroll as usize);
frame.render_stateful_widget(
Scrollbar::new(ScrollbarOrientation::VerticalRight),
area.inner(Margin { vertical: 1, horizontal: 0 }),
&mut sb_state,
);
}
}
// ---------------------------------------------------------------------------
// SectionTree — expand/collapse tree renderer for ContextSection
// ---------------------------------------------------------------------------
pub struct SectionTree {
pub selected: Option<usize>,
pub expanded: std::collections::HashSet<usize>,
pub scroll: u16,
}
impl SectionTree {
pub fn new() -> Self {
Self { selected: None, expanded: std::collections::HashSet::new(), scroll: 0 }
}
/// Total nodes in the tree (regardless of expand state).
/// Each section is 1 node, each entry within is 1 node.
fn total_nodes(&self, sections: &[ContextSection]) -> usize {
sections.iter().map(|s| 1 + s.entries().len()).sum()
}
pub fn item_count(&self, sections: &[ContextSection]) -> usize {
let mut idx = 0;
let mut total = 0;
for section in sections {
let my_idx = idx;
idx += 1;
total += 1;
if self.expanded.contains(&my_idx) {
total += section.entries().len();
idx += section.entries().len();
}
}
total
}
pub fn handle_nav(&mut self, code: KeyCode, sections: &[ContextSection], height: u16) {
let item_count = self.item_count(sections);
let page = height.saturating_sub(2) as usize; // account for border
match code {
KeyCode::Up => {
self.selected = Some(self.selected.unwrap_or(0).saturating_sub(1));
}
KeyCode::Down => {
let max = item_count.saturating_sub(1);
self.selected = Some(self.selected.map_or(0, |s| (s + 1).min(max)));
}
KeyCode::PageUp => {
let sel = self.selected.unwrap_or(0);
self.selected = Some(sel.saturating_sub(page));
self.scroll = self.scroll.saturating_sub(page as u16);
return; // skip scroll_to_selected — we moved both together
}
KeyCode::PageDown => {
let max = item_count.saturating_sub(1);
let sel = self.selected.map_or(0, |s| (s + page).min(max));
self.selected = Some(sel);
self.scroll += page as u16;
return;
}
KeyCode::Home => {
self.selected = Some(0);
}
KeyCode::End => {
self.selected = Some(item_count.saturating_sub(1));
}
KeyCode::Right | KeyCode::Enter => {
if let Some(sel) = self.selected {
self.expanded.insert(sel);
}
}
KeyCode::Left => {
if let Some(sel) = self.selected {
self.expanded.remove(&sel);
}
}
KeyCode::Char('e') => {
// Expand all
let total = self.total_nodes(sections);
for i in 0..total {
self.expanded.insert(i);
}
}
KeyCode::Char('c') => {
// Collapse all
self.expanded.clear();
}
_ => {}
}
self.scroll_to_selected(height);
}
fn scroll_to_selected(&mut self, height: u16) {
if let Some(sel) = self.selected {
let sel_line = sel as u16;
let visible = height.saturating_sub(2); // border
if sel_line < self.scroll {
self.scroll = sel_line;
} else if sel_line >= self.scroll + visible {
self.scroll = sel_line.saturating_sub(visible.saturating_sub(1));
}
}
}
pub fn render_sections(&self, sections: &[ContextSection], lines: &mut Vec<Line>) {
let mut idx = 0;
for section in sections {
self.render_one(section, lines, &mut idx);
}
}
fn render_one(
&self,
section: &ContextSection,
lines: &mut Vec<Line>,
idx: &mut usize,
) {
let my_idx = *idx;
let selected = self.selected == Some(my_idx);
let expanded = self.expanded.contains(&my_idx);
let expandable = !section.is_empty();
let marker = if !expandable { " " } else if expanded { "" } else { "" };
let label = format!(" {} {:30} {:>6} tokens",
marker, format!("{} ({})", section.name, section.len()), section.tokens());
let style = if selected {
Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
} else {
Style::default()
};
lines.push(Line::styled(label, style));
*idx += 1;
if expanded {
for ce in section.entries() {
let entry_selected = self.selected == Some(*idx);
let entry_expanded = self.expanded.contains(idx);
let text = ce.entry.message().content_text();
let preview: String = text.chars().take(60).collect();
let preview = preview.replace('\n', " ");
let label = if preview.len() < text.len() {
format!(" {}...", preview)
} else {
format!(" {}", preview)
};
let entry_marker = if text.len() > 60 {
if entry_expanded { "" } else { "" }
} else { " " };
let entry_label = format!(" {} {:>6} {}", entry_marker, ce.tokens, label);
let style = if entry_selected {
Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Color::DarkGray)
};
lines.push(Line::styled(entry_label, style));
*idx += 1;
if entry_expanded {
let content_lines: Vec<&str> = text.lines().collect();
let show = content_lines.len().min(50);
for line in &content_lines[..show] {
lines.push(Line::styled(
format!("{}", line),
Style::default().fg(Color::DarkGray),
));
}
if content_lines.len() > 50 {
lines.push(Line::styled(
format!(" ... ({} more lines)", content_lines.len() - 50),
Style::default().fg(Color::DarkGray),
));
}
}
}
}
}
}