feat: add unified popup framework with content-sized boxes

This commit is contained in:
objz committed 2025-07-19 17:18:29 +02:00
1 parent 96b6f4e0e9
commit c06dd5c3ca
4 files changed
+304 -15

No files matched your search

+22 -15
View File
@@ -1,32 +1,39 @@
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Style,
layout::{Alignment, Rect},
style::{Color, Style},
text::Line,
widgets::{Block, Borders, Clear, Widget},
widgets::{Block, BorderType, Borders, Clear, Widget},
};
pub struct Popup<'a> {
pub struct PopupFrame<'a> {
pub title: Line<'a>,
pub border_style: Style,
pub title_style: Style,
pub style: Style,
pub border_color: Color,
pub bg: Option<Color>,
pub keybinds: Option<Line<'a>>,
pub content: Box<dyn Fn(Rect, &mut Buffer) + 'a>,
}
impl<'a> Widget for Popup<'a> {
impl<'a> Widget for PopupFrame<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let block = Block::new()
.title(self.title)
.title_style(self.title_style)
if let Some(bg) = self.bg {
buf.set_style(area, Style::default().bg(bg));
}
let mut block = Block::default()
.title_top(self.title)
.borders(Borders::ALL)
.border_style(self.border_style);
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(self.border_color));
let inner_area = block.inner(area);
if let Some(kb) = self.keybinds {
block = block.title_bottom(kb.alignment(Alignment::Right));
}
let inner = block.inner(area);
block.render(area, buf);
(self.content)(inner_area, buf);
(self.content)(inner, buf);
}
}
+99
View File
@@ -0,0 +1,99 @@
use once_cell::sync::Lazy;
use std::sync::Mutex;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Modifier, Style},
text::{Line, Span},
widgets::{Paragraph, Widget},
};
use crate::tui::theme::THEME;
static CONFIRM_STATE: Lazy<Mutex<ConfirmState>> = Lazy::new(|| Mutex::new(ConfirmState::default()));
#[derive(Debug, Default)]
struct ConfirmState {
instance_name: String,
}
pub fn set_pending_delete(name: impl Into<String>) {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name = name.into();
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
}
}
}
pub fn pending_delete_name() -> String {
match CONFIRM_STATE.lock() {
Ok(s) => s.instance_name.clone(),
Err(_) => String::new(),
}
}
pub fn clear_pending() {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name.clear();
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
}
}
}
pub struct ConfirmPopup {
instance_name: String,
}
impl ConfirmPopup {
pub fn new(instance_name: impl Into<String>) -> Self {
Self {
instance_name: instance_name.into(),
}
}
}
impl Widget for ConfirmPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
use super::{base::PopupFrame, keybind_line};
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
Style::default()
.fg(THEME.colors.border_focused)
.add_modifier(Modifier::BOLD),
)]);
let kb = keybind_line(&[("y", " yes"), ("n", " no")]);
let popup = PopupFrame {
title,
border_color: THEME.colors.border_focused,
bg: Some(THEME.colors.row_alternate_bg),
keybinds: Some(kb),
content: Box::new(|inner, buf| {
Paragraph::new("This will permanently remove the instance")
.style(Style::default().fg(THEME.colors.foreground))
.render(inner, buf);
}),
};
popup.render(area, buf);
}
}
pub fn confirm_popup_area(frame_area: Rect, name: &str) -> Rect {
use super::{centered_rect, word_wrap_size};
const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance";
let title_w = name.len() + 12;
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(BODY, inner_w);
centered_rect(frame_area, inner_w, lines)
}
+103
View File
@@ -0,0 +1,103 @@
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Paragraph, Widget, Wrap},
};
use tracing::Level;
use super::base::PopupFrame;
use crate::tui::error_buffer::ErrorEvent;
use crate::tui::theme::THEME;
pub struct ErrorPopup {
pub event: ErrorEvent,
}
impl ErrorPopup {
pub fn new(event: ErrorEvent) -> Self {
Self { event }
}
}
impl Widget for ErrorPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
let (border_color, label) = match self.event.level {
Level::ERROR => (Color::Red, "ERROR"),
Level::WARN => (Color::Yellow, "WARN"),
_ => (THEME.colors.border_focused, "INFO"),
};
let title = Line::from(vec![Span::styled(
format!(" {} ", label),
Style::default()
.fg(Color::Black)
.bg(border_color)
.add_modifier(Modifier::BOLD),
)]);
let message = self.event.message.clone();
let popup = PopupFrame {
title,
border_color,
bg: None,
keybinds: None,
content: Box::new(move |inner, buf| {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.colors.foreground))
.render(inner, buf);
}),
};
popup.render(area, buf);
}
}
pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128) -> Option<Rect> {
use super::word_wrap_size;
const MAX_W: usize = 58;
const MIN_W: usize = 22;
const SLIDE_START_MS: u128 = 3500;
const DISMISS_MS: u128 = 5000;
if elapsed_ms >= DISMISS_MS {
return None;
}
let (w, h) = word_wrap_size(message, MAX_W);
let inner_w = w.max(MIN_W);
let popup_w = (inner_w + 2) as u16;
let popup_h = (h + 2) as u16;
let popup_w = popup_w.min(frame_area.width.saturating_sub(4));
let popup_h = popup_h.min(frame_area.height.saturating_sub(2));
let base_x = frame_area.width.saturating_sub(popup_w + 2);
if elapsed_ms < SLIDE_START_MS {
return Some(Rect {
x: base_x,
y: base_y,
width: popup_w,
height: popup_h,
});
}
let progress = (elapsed_ms - SLIDE_START_MS) as f32 / (DISMISS_MS - SLIDE_START_MS) as f32;
let slide = (progress * popup_w as f32) as u16;
let new_x = base_x.saturating_add(slide);
if new_x >= frame_area.width {
return None;
}
let visible_w = frame_area.width.saturating_sub(new_x);
Some(Rect {
x: new_x,
y: base_y,
width: visible_w.min(popup_w),
height: popup_h,
})
}
+80
View File
@@ -1,2 +1,82 @@
pub mod base;
pub mod confirm;
pub mod error;
pub mod new_instance;
use ratatui::layout::Rect;
/// Calculates the minimum inner dimensions needed to display `text` with word-boundary wrapping
/// inside a box of `max_inner_width` columns.
///
/// Returns `(actual_inner_width, line_count)` where:
/// - `actual_inner_width` is the width of the widest wrapped line (never exceeds `max_inner_width`)
/// - `line_count` is how many lines are needed
///
/// Add 2 to each dimension for borders: popup_w = actual_inner_width + 2, popup_h = line_count + 2.
pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
if text.is_empty() || max_inner_width == 0 {
return (0, 1);
}
let mut lines: usize = 1;
let mut current_line_len: usize = 0;
let mut widest_line: usize = 0;
for word in text.split_whitespace() {
let word_len = word.len().min(max_inner_width);
if current_line_len == 0 {
current_line_len = word_len;
} else if current_line_len + 1 + word_len <= max_inner_width {
current_line_len += 1 + word_len;
} else {
widest_line = widest_line.max(current_line_len);
lines += 1;
current_line_len = word_len;
}
}
widest_line = widest_line.max(current_line_len);
(widest_line, lines)
}
pub fn centered_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
let popup_w = (inner_w + 2) as u16;
let popup_h = (inner_h + 2) as u16;
let popup_w = popup_w.min(frame.width.saturating_sub(4));
let popup_h = popup_h.min(frame.height.saturating_sub(4));
let x = (frame.width.saturating_sub(popup_w)) / 2;
let y = (frame.height.saturating_sub(popup_h)) / 2;
Rect { x, y, width: popup_w, height: popup_h }
}
pub fn top_right_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
let popup_w = (inner_w + 2) as u16;
let popup_h = (inner_h + 2) as u16;
let popup_w = popup_w.min(frame.width.saturating_sub(4));
let popup_h = popup_h.min(frame.height.saturating_sub(2));
let x = frame.width.saturating_sub(popup_w + 2);
let y = 1u16;
Rect { x, y, width: popup_w, height: popup_h }
}
pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
use ratatui::{style::{Modifier, Style}, text::{Line, Span}};
use crate::tui::theme::THEME;
let key_style = Style::default()
.fg(THEME.colors.border_focused)
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(THEME.colors.border_unfocused);
let mut spans: Vec<Span<'static>> = Vec::new();
for (i, (key, label)) in binds.iter().enumerate() {
if i > 0 {
spans.push(Span::styled(" ", dim_style));
}
spans.push(Span::styled(format!("[{}]", key), key_style));
if !label.is_empty() {
spans.push(Span::styled(label.to_string(), dim_style));
}
}
Line::from(spans)
}