//! Modal dialog widget. use crate::{ActionBar, ActionList, overlay_area}; use rustik_tui_core as tui_core; use tui_core::{ Border, BorderChars, Buffer, Cell, Color, Constraint, Line, Rect, Size, Style, Widget, colors, }; /// Default maximum dialog panel size. pub const DEFAULT_DIALOG_MAX_SIZE: Size = Size::new(72, 12); /// Default minimum margin around a dialog panel. pub const DEFAULT_DIALOG_MARGIN: Size = Size::new(2, 1); /// Horizontal padding inside the dialog frame. const DIALOG_PADDING: usize = 1; /// Square border glyphs used by modal dialogs. const DIALOG_BORDER_CHARS: BorderChars = BorderChars { top_left: '┌', top_right: '┐', bottom_left: '└', bottom_right: '┘', vertical: '│', horizontal: '─', divider_left: '├', divider_right: '┤', }; /// Visual treatment for a dialog. #[derive(Debug, Clone, Copy, Default, Eq, PartialEq)] pub enum DialogKind { /// Neutral dialog. #[default] Normal, /// Error dialog with negative chrome. Error, } impl DialogKind { /// Returns the foreground color used for dialog chrome. fn color(self) -> Color { match self { Self::Normal => colors::FAINT, Self::Error => colors::rgb::NEGATIVE_LIGHT, } } /// Returns the border used by the dialog. fn border(self) -> Border { Border { style: Style::new(self.color()), chars: DIALOG_BORDER_CHARS, } } /// Returns the heading style. fn heading_style(self) -> Style { match self { Self::Normal => Style::default(), Self::Error => Style::new(self.color()).bold(), } } /// Returns an action bar for this dialog kind. fn action_bar(self, actions: ActionList) -> ActionBar { ActionBar::new(actions) .cap_style(Style::new(self.key_background())) .key_style(self.key_style()) .action_style(self.action_style()) } /// Returns the background color used for shortcut pills. fn key_background(self) -> Color { match self { Self::Normal => self.color(), Self::Error => Color::Fixed(250), } } /// Returns the style used for action key text. fn key_style(self) -> Style { match self { Self::Normal => Style::new(Color::White).bg(self.color()).bold(), Self::Error => Style::new(Color::Black).bg(self.key_background()).bold(), } } /// Returns the style used for action labels. fn action_style(self) -> Style { match self { Self::Normal => Style::new(colors::fixed::DIM), Self::Error => Style::new(Color::Fixed(244)), } } } /// Centered modal dialog with body text and an optional action bar. #[derive(Debug, Clone)] pub struct Dialog { /// Dialog heading shown as the first content row. heading: Line, /// Dialog visual treatment. kind: DialogKind, /// Body lines rendered above the actions. body: Vec, /// Action metadata rendered as key hints. actions: ActionList, /// Cell used to clear the dialog panel. background: Cell, /// Largest panel size. max_size: Size, /// Minimum parent-space margin kept around the panel. margin: Size, } impl Dialog { /// Creates an empty dialog with `heading`. pub fn new(heading: impl Into) -> Self { Self { heading: heading.into(), kind: DialogKind::Normal, body: Vec::new(), actions: ActionList::new(), background: Cell::blank(), max_size: DEFAULT_DIALOG_MAX_SIZE, margin: DEFAULT_DIALOG_MARGIN, } } /// Creates an error dialog. pub fn error() -> Self { Self::new("ERROR").kind(DialogKind::Error) } /// Sets the dialog visual treatment. pub const fn kind(mut self, kind: DialogKind) -> Self { self.kind = kind; self } /// Sets the body lines. pub fn body(mut self, body: impl IntoIterator) -> Self { self.body = body.into_iter().collect(); self } /// Adds one body line. pub fn body_line(mut self, line: impl Into) -> Self { self.body.push(line.into()); self } /// Sets the action list. pub fn actions(mut self, actions: ActionList) -> Self { self.actions = actions; self } /// Sets the cell used to clear the dialog panel. pub fn background(mut self, cell: Cell) -> Self { self.background = cell; self } /// 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 } /// Returns the largest panel size available inside `area`. fn available_max(&self, area: Rect) -> Size { Size::new( self.max_size .cols .min(area.cols.saturating_sub(self.margin.cols.saturating_mul(2))), self.max_size .rows .min(area.rows.saturating_sub(self.margin.rows.saturating_mul(2))), ) } /// Returns the dialog size under `max`. fn panel_size(&self, max: Size) -> Size { let action = self.action_line(); let body_width = self.body.iter().map(Line::width).max().unwrap_or_default(); let content_width = self.heading.width().max(body_width).max(action.width()); let content_rows = 1 + usize::from(!self.body.is_empty() || !self.actions.items().is_empty()) + self.body.len() + if self.actions.items().is_empty() { 0 } else { 2 }; let size = Size::new( content_width .saturating_add(DIALOG_PADDING.saturating_mul(2)) .saturating_add(2), content_rows.saturating_add(2), ); let min = Size::new(2.min(max.cols), 2.min(max.rows)); size.constrain(Constraint::new(min, max)) } /// Returns the rendered action line. fn action_line(&self) -> Line { self.kind.action_bar(self.actions.clone()).line() } /// Renders the dialog heading. fn render_heading(&self, area: Rect, buf: &mut Buffer) { let heading = self.heading.clone().style(self.kind.heading_style()); Line::renders([heading], area, buf); } /// Renders dialog body lines without entering the reserved action rows. fn render_body(&self, area: Rect, buf: &mut Buffer) { Line::renders(self.body.iter().take(area.rows).cloned(), area, buf); } /// Renders the action row at the bottom of the dialog. fn render_actions(&self, area: Rect, buf: &mut Buffer) { if self.actions.items().is_empty() { return; } Line::renders([self.action_line()], area, buf); } } impl Widget for Dialog { fn size(&self, parent: Constraint) -> Size { parent.bounded_size() } fn render(&mut self, area: Rect, buf: &mut Buffer) { let max = self.available_max(area); let size = self.panel_size(max); let area = overlay_area(area, size, self.margin); if area.is_empty() { return; } buf.fill(area, self.background.clone()); self.kind.border().draw(area, buf); let content = area.inner(1); let content_cols = content .cols .saturating_sub(DIALOG_PADDING.saturating_mul(2)); let content_x = content.x + DIALOG_PADDING.min(content.cols); let heading_area = Rect::new(content_x, content.y, content_cols, 1); self.render_heading(heading_area, buf); let action_area = if self.actions.items().is_empty() || content.rows < 2 { Rect::ZERO } else { Rect::new( content_x, content.bottom().saturating_sub(1), content_cols, 1, ) }; let body_y = content.y.saturating_add(2); let body_bottom = if action_area.is_empty() { content.bottom() } else { action_area.y.saturating_sub(1) }; let body_area = Rect::new( content_x, body_y, content_cols, body_bottom.saturating_sub(body_y), ); self.render_body(body_area, buf); self.render_actions(action_area, buf); } } #[cfg(test)] mod tests { use super::*; use tui_core::{Buffer, Rect}; #[test] fn error_dialog_uses_negative_chrome() { let mut dialog = Dialog::error() .body_line("State mismatch") .max_size(Size::new(24, 6)) .margin(Size::MIN); let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7)); dialog.render(buffer.area(), &mut buffer); assert!(first_position_with_foreground(&buffer, colors::rgb::NEGATIVE_LIGHT).is_some()); } #[test] fn dialog_keeps_actions_visible_when_body_is_taller_than_panel() { let body = [ Line::new("one"), Line::new("two"), Line::new("three"), Line::new("four"), Line::new("five"), ]; let mut dialog = Dialog::error() .body(body) .actions(ActionList::new().action("r", "reset").action("q", "quit")) .max_size(Size::new(30, 7)) .margin(Size::MIN); let mut buffer = Buffer::empty(Rect::new(0, 0, 34, 9)); dialog.render(buffer.area(), &mut buffer); assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_some()); } #[test] fn tiny_dialog_drops_actions_instead_of_overwriting_the_heading() { let mut dialog = Dialog::error() .actions(ActionList::new().action("q", "quit")) .max_size(Size::new(24, 3)) .margin(Size::MIN); let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 3)); dialog.render(buffer.area(), &mut buffer); assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_none()); } #[test] fn error_dialog_actions_use_grey_pills_black_keys_and_lighter_labels() { let mut dialog = Dialog::error() .actions(ActionList::new().action("r", "reset")) .max_size(Size::new(24, 5)) .margin(Size::MIN); let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7)); dialog.render(buffer.area(), &mut buffer); let key = first_foreground_with_background(&buffer, Color::Fixed(250)); let label = first_position_with_foreground(&buffer, Color::Fixed(244)); assert_eq!(key, Some(Color::Black)); assert!(label.is_some()); } /// Returns the first position whose foreground color is `foreground`. fn first_position_with_foreground( buffer: &Buffer, foreground: Color, ) -> Option<(usize, usize)> { for y in 0..buffer.area().rows { for x in 0..buffer.area().cols { let Some(cell) = buffer.get(x, y) else { continue; }; if cell.style().fg_color() == foreground { return Some((x, y)); } } } None } /// Returns the first position whose background color is `background`. fn first_position_with_background( buffer: &Buffer, background: Color, ) -> Option<(usize, usize)> { for y in 0..buffer.area().rows { for x in 0..buffer.area().cols { let Some(cell) = buffer.get(x, y) else { continue; }; if cell.style().bg_color() == background { return Some((x, y)); } } } None } /// Returns the foreground color of the first cell with `background`. fn first_foreground_with_background(buffer: &Buffer, background: Color) -> Option { for y in 0..buffer.area().rows { for x in 0..buffer.area().cols { let Some(cell) = buffer.get(x, y) else { continue; }; if cell.style().bg_color() == background { return Some(cell.style().fg_color()); } } } None } }