1use ratatui::buffer::Buffer;
4use ratatui::layout::{Margin, Rect};
5use ratatui::widgets::{Clear, Widget};
6
7use crate::button::{HEIGHT, Look};
8use crate::chrome::{FrameMode, FrameState, close_area, draw_icon};
9use crate::frame::{dialog, shadow};
10use crate::{Button, Role, Theme, render_scrollbar};
11
12const BUTTON_GAP: u16 = 2;
14
15const MESSAGE_SIZE: (u16, u16) = (40, 9);
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub enum ButtonRow {
22 #[default]
23 Centred,
24 BottomRight,
25}
26
27pub struct Dialog<'a> {
30 theme: &'a Theme,
31 title: &'a str,
32 buttons: &'a [Button<'a>],
33 focused: Option<usize>,
34 pressed: Option<usize>,
35 row: ButtonRow,
36 bar: Option<(usize, usize, usize)>,
37 mode: FrameMode,
38}
39
40impl<'a> Dialog<'a> {
41 #[must_use]
42 pub fn new(theme: &'a Theme, title: &'a str, buttons: &'a [Button<'a>]) -> Self {
43 Dialog {
44 theme,
45 title,
46 buttons,
47 focused: None,
48 pressed: None,
49 row: ButtonRow::default(),
50 bar: None,
51 mode: FrameMode::Active,
52 }
53 }
54
55 #[must_use]
57 pub fn focused(mut self, index: Option<usize>) -> Self {
58 self.focused = index;
59 self
60 }
61
62 #[must_use]
64 pub fn dragging(mut self, dragging: bool) -> Self {
65 if dragging {
66 self.mode = FrameMode::Dragging;
67 }
68 self
69 }
70
71 #[must_use]
74 pub fn inactive(mut self, inactive: bool) -> Self {
75 if inactive {
76 self.mode = FrameMode::Passive;
77 }
78 self
79 }
80
81 #[must_use]
83 pub fn pressed(mut self, index: Option<usize>) -> Self {
84 self.pressed = index;
85 self
86 }
87
88 #[must_use]
90 pub fn button_row_width(buttons: &[Button<'_>]) -> u16 {
91 row_width(buttons.iter().map(Button::width))
92 }
93
94 #[must_use]
96 pub fn row(mut self, row: ButtonRow) -> Self {
97 self.row = row;
98 self
99 }
100
101 pub const BUTTON_ROWS: u16 = 1 + HEIGHT;
103
104 #[must_use]
106 pub fn body_area(area: Rect) -> Rect {
107 let inner = area.inner(Margin::new(1, 1));
108 Rect {
109 height: inner.height.saturating_sub(Self::BUTTON_ROWS),
110 ..inner
111 }
112 }
113
114 #[must_use]
117 pub fn close_area(area: Rect) -> Option<Rect> {
118 let state = FrameState {
119 mode: FrameMode::Active,
120 ..FrameState::default()
121 };
122 close_area(area, state)
123 }
124
125 #[must_use]
128 pub fn min_size(buttons: &[Button<'_>], row: ButtonRow) -> (u16, u16) {
129 let spare = match row {
130 ButtonRow::Centred => 2,
131 ButtonRow::BottomRight => 3,
132 };
133 let row = Self::button_row_width(buttons).saturating_add(spare);
134 (row, 3 + Self::BUTTON_ROWS)
135 }
136
137 #[must_use]
140 pub fn fitted(
141 (widest, rows): (usize, usize),
142 buttons: &[Button<'_>],
143 row: ButtonRow,
144 full: Rect,
145 ) -> Rect {
146 let (min_width, min_height) = Self::min_size(buttons, row);
147 let width = u16::try_from(widest + 4).unwrap_or(u16::MAX);
148 let height = u16::try_from(rows + 2 + usize::from(Self::BUTTON_ROWS)).unwrap_or(u16::MAX);
149 centred(full, width.max(min_width), height.max(min_height))
150 }
151
152 #[must_use]
155 pub fn message_box(text_len: usize, buttons: &[Button<'_>], full: Rect) -> Rect {
156 let columns = usize::from(MESSAGE_SIZE.0 - 7);
157 let height = match text_len > columns * usize::from(MESSAGE_SIZE.1 - 6) {
158 true => u16::try_from(text_len / columns + 7).unwrap_or(u16::MAX),
159 false => MESSAGE_SIZE.1,
160 };
161 let (min_width, _) = Self::min_size(buttons, ButtonRow::Centred);
162 centred(full, MESSAGE_SIZE.0.max(min_width), height)
163 }
164
165 #[must_use]
168 pub fn message_area(area: Rect) -> Rect {
169 Rect::new(
170 area.x.saturating_add(3),
171 area.y.saturating_add(2),
172 area.width.saturating_sub(5),
173 area.height.saturating_sub(5),
174 )
175 }
176
177 #[must_use]
180 pub fn scrollbar(mut self, rows: usize, view: usize, top: usize) -> Self {
181 self.bar = Some((rows, view, top));
182 self
183 }
184
185 #[must_use]
188 pub fn scrollbar_frame(area: Rect) -> Rect {
189 let body = Self::body_area(area);
190 Rect {
191 y: body.y.saturating_sub(1),
192 height: body.height.saturating_add(2),
193 ..area
194 }
195 }
196
197 #[must_use]
202 pub fn button_areas(area: Rect, buttons: &[Button<'_>], row: ButtonRow) -> Vec<Rect> {
203 let inner = area.inner(Margin::new(1, 1));
204 if inner.height < HEIGHT {
205 return Vec::new();
206 }
207 let strip = Rect::new(inner.x, inner.bottom() - HEIGHT, inner.width, HEIGHT);
208 let widths: Vec<u16> = buttons.iter().map(Button::width).collect();
209 let total = row_width(widths.iter().copied());
210 let start = match row {
211 ButtonRow::Centred => strip
212 .x
213 .saturating_add(strip.width.saturating_sub(total) / 2),
214 ButtonRow::BottomRight => strip
215 .right()
216 .saturating_sub(total.saturating_add(1))
217 .max(strip.x),
218 };
219 let mut x = start;
220 let mut areas = Vec::with_capacity(buttons.len());
221 for width in widths {
222 areas.push(Rect::new(x, strip.y, width, HEIGHT).intersection(strip));
223 x = x.saturating_add(width).saturating_add(BUTTON_GAP);
224 }
225 areas
226 }
227}
228
229fn centred(full: Rect, width: u16, height: u16) -> Rect {
231 let (width, height) = (width.min(full.width), height.min(full.height));
232 Rect::new(
233 full.x + (full.width - width) / 2,
234 full.y + (full.height - height) / 2,
235 width,
236 height,
237 )
238}
239
240fn row_width(widths: impl ExactSizeIterator<Item = u16>) -> u16 {
241 let gaps = u16::try_from(widths.len().saturating_sub(1)).unwrap_or(u16::MAX);
242 widths.fold(BUTTON_GAP.saturating_mul(gaps), u16::saturating_add)
243}
244
245impl Widget for Dialog<'_> {
246 fn render(self, area: Rect, buf: &mut Buffer) {
247 let outer = area.intersection(buf.area);
248 Clear.render(outer, buf);
249 dialog(self.theme, self.title, self.mode).render(outer, buf);
250 let passive = self.mode == FrameMode::Passive;
251 if let Some(icon) = Self::close_area(outer).filter(|_| !passive) {
252 let frame = if self.mode == FrameMode::Dragging {
253 Role::DialogIcon
254 } else {
255 Role::DialogFrame
256 };
257 let styles = [frame, Role::DialogIcon].map(|role| self.theme.style(role));
258 draw_icon(buf, icon, "\u{25A0}", styles);
259 }
260 let cells = Self::button_areas(area, self.buttons, self.row);
261 for (i, (button, cell)) in self.buttons.iter().zip(cells).enumerate() {
262 let button = Button {
263 default: button.default && self.focused.is_none() && !passive,
264 ..*button
265 };
266 let look = Look {
267 focused: self.focused == Some(i) && !passive,
268 pressed: self.pressed == Some(i) && !passive,
269 };
270 button.render(cell, buf, self.theme, look);
271 }
272 if let Some(dims) = self.bar {
273 render_scrollbar(self.theme, Self::scrollbar_frame(area), buf, dims);
274 }
275 shadow(buf, outer, self.theme);
276 }
277}
278
279#[cfg(test)]
280mod message_box_tests;
281#[cfg(test)]
282mod tests;