//! Centered overlay widget. use rustik_tui_core as tui_core; use tui_core::{Buffer, Cell, Constraint, Rect, Size, Widget}; /// Centered child widget rendered over a filled panel area. #[derive(Debug, Clone)] pub struct Overlay { /// Child rendered inside the overlay panel. child: W, /// Largest panel size. max_size: Size, /// Minimum parent-space margin kept around the panel. margin: Size, /// Cell used to fill the panel before rendering the child. background: Cell, } impl Overlay { /// Creates an overlay around a child widget. pub fn new(child: W) -> Self { Self { child, max_size: Size::MAX, margin: Size::MIN, background: Cell::blank(), } } /// Sets the largest panel size. pub const fn max_size(mut self, size: Size) -> Self { self.max_size = size; self } /// Sets the minimum parent-space margin around the panel. pub const fn margin(mut self, margin: Size) -> Self { self.margin = margin; self } /// Sets the cell used to fill the panel. pub fn background(mut self, cell: Cell) -> Self { self.background = cell; self } /// Returns the panel area inside a parent area. pub fn area(&self, area: Rect) -> Rect { overlay_area(area, self.max_size, self.margin) } } impl Widget for Overlay { fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render(&mut self, area: Rect, buf: &mut Buffer) { let area = self.area(area); if area.is_empty() { return; } buf.fill(area, self.background.clone()); self.child.render(area, buf); } } /// Returns a centered overlay panel area inside `area`. pub fn overlay_area(area: Rect, max_size: Size, margin: Size) -> Rect { let available_cols = area.cols.saturating_sub(margin.cols.saturating_mul(2)); let available_rows = area.rows.saturating_sub(margin.rows.saturating_mul(2)); let cols = max_size.cols.min(available_cols); let rows = max_size.rows.min(available_rows); Rect::new( area.x + area.cols.saturating_sub(cols) / 2, area.y + area.rows.saturating_sub(rows) / 2, cols, rows, ) } #[cfg(test)] mod tests { use super::*; use rustik_tui_core::{Buffer, Cell, Color, Constraint, Label, Rect, Size, Style, Widget}; #[test] fn overlay_area_centers_with_max_size_and_margin() { let area = overlay_area(Rect::new(0, 0, 120, 40), Size::new(96, 18), Size::new(4, 4)); assert_eq!(area, Rect::new(12, 11, 96, 18)); } #[test] fn overlay_fills_background_and_renders_child() { let background = Cell::new('.', Style::new(Color::Blue)); let mut overlay = Overlay::new(Label::new("hi")) .max_size(Size::new(6, 3)) .margin(Size::new(2, 1)) .background(background); let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 5)); overlay.render(buffer.area(), &mut buffer); assert_eq!(overlay.size(Constraint::max(buffer.size())), buffer.size()); assert_eq!( buffer.lines(), vec![ " ", " hi.... ", " ...... ", " ...... ", " " ] ); } }