crates/tui-widgets/src/dialog.rs 12.4 KiB raw
1
//! Modal dialog widget.
2
3
use crate::{ActionBar, ActionList, overlay_area};
4
use rustik_tui_core as tui_core;
5
use tui_core::{
6
    Border, BorderChars, Buffer, Cell, Color, Constraint, Line, Rect, Size, Style, Widget, colors,
7
};
8
9
/// Default maximum dialog panel size.
10
pub const DEFAULT_DIALOG_MAX_SIZE: Size = Size::new(72, 12);
11
/// Default minimum margin around a dialog panel.
12
pub const DEFAULT_DIALOG_MARGIN: Size = Size::new(2, 1);
13
14
/// Horizontal padding inside the dialog frame.
15
const DIALOG_PADDING: usize = 1;
16
/// Square border glyphs used by modal dialogs.
17
const DIALOG_BORDER_CHARS: BorderChars = BorderChars {
18
    top_left: '┌',
19
    top_right: '┐',
20
    bottom_left: '└',
21
    bottom_right: '┘',
22
    vertical: '│',
23
    horizontal: '─',
24
    divider_left: '├',
25
    divider_right: '┤',
26
};
27
28
/// Visual treatment for a dialog.
29
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
30
pub enum DialogKind {
31
    /// Neutral dialog.
32
    #[default]
33
    Normal,
34
    /// Error dialog with negative chrome.
35
    Error,
36
}
37
38
impl DialogKind {
39
    /// Returns the foreground color used for dialog chrome.
40
    fn color(self) -> Color {
41
        match self {
42
            Self::Normal => colors::FAINT,
43
            Self::Error => colors::rgb::NEGATIVE_LIGHT,
44
        }
45
    }
46
47
    /// Returns the border used by the dialog.
48
    fn border(self) -> Border {
49
        Border {
50
            style: Style::new(self.color()),
51
            chars: DIALOG_BORDER_CHARS,
52
        }
53
    }
54
55
    /// Returns the heading style.
56
    fn heading_style(self) -> Style {
57
        match self {
58
            Self::Normal => Style::default(),
59
            Self::Error => Style::new(self.color()).bold(),
60
        }
61
    }
62
63
    /// Returns an action bar for this dialog kind.
64
    fn action_bar(self, actions: ActionList) -> ActionBar {
65
        ActionBar::new(actions)
66
            .cap_style(Style::new(self.key_background()))
67
            .key_style(self.key_style())
68
            .action_style(self.action_style())
69
    }
70
71
    /// Returns the background color used for shortcut pills.
72
    fn key_background(self) -> Color {
73
        match self {
74
            Self::Normal => self.color(),
75
            Self::Error => Color::Fixed(250),
76
        }
77
    }
78
79
    /// Returns the style used for action key text.
80
    fn key_style(self) -> Style {
81
        match self {
82
            Self::Normal => Style::new(Color::White).bg(self.color()).bold(),
83
            Self::Error => Style::new(Color::Black).bg(self.key_background()).bold(),
84
        }
85
    }
86
87
    /// Returns the style used for action labels.
88
    fn action_style(self) -> Style {
89
        match self {
90
            Self::Normal => Style::new(colors::fixed::DIM),
91
            Self::Error => Style::new(Color::Fixed(244)),
92
        }
93
    }
94
}
95
96
/// Centered modal dialog with body text and an optional action bar.
97
#[derive(Debug, Clone)]
98
pub struct Dialog {
99
    /// Dialog heading shown as the first content row.
100
    heading: Line,
101
    /// Dialog visual treatment.
102
    kind: DialogKind,
103
    /// Body lines rendered above the actions.
104
    body: Vec<Line>,
105
    /// Action metadata rendered as key hints.
106
    actions: ActionList,
107
    /// Cell used to clear the dialog panel.
108
    background: Cell,
109
    /// Largest panel size.
110
    max_size: Size,
111
    /// Minimum parent-space margin kept around the panel.
112
    margin: Size,
113
}
114
115
impl Dialog {
116
    /// Creates an empty dialog with `heading`.
117
    pub fn new(heading: impl Into<Line>) -> Self {
118
        Self {
119
            heading: heading.into(),
120
            kind: DialogKind::Normal,
121
            body: Vec::new(),
122
            actions: ActionList::new(),
123
            background: Cell::blank(),
124
            max_size: DEFAULT_DIALOG_MAX_SIZE,
125
            margin: DEFAULT_DIALOG_MARGIN,
126
        }
127
    }
128
129
    /// Creates an error dialog.
130
    pub fn error() -> Self {
131
        Self::new("ERROR").kind(DialogKind::Error)
132
    }
133
134
    /// Sets the dialog visual treatment.
135
    pub const fn kind(mut self, kind: DialogKind) -> Self {
136
        self.kind = kind;
137
        self
138
    }
139
140
    /// Sets the body lines.
141
    pub fn body(mut self, body: impl IntoIterator<Item = Line>) -> Self {
142
        self.body = body.into_iter().collect();
143
        self
144
    }
145
146
    /// Adds one body line.
147
    pub fn body_line(mut self, line: impl Into<Line>) -> Self {
148
        self.body.push(line.into());
149
        self
150
    }
151
152
    /// Sets the action list.
153
    pub fn actions(mut self, actions: ActionList) -> Self {
154
        self.actions = actions;
155
        self
156
    }
157
158
    /// Sets the cell used to clear the dialog panel.
159
    pub fn background(mut self, cell: Cell) -> Self {
160
        self.background = cell;
161
        self
162
    }
163
164
    /// Sets the largest panel size.
165
    pub const fn max_size(mut self, size: Size) -> Self {
166
        self.max_size = size;
167
        self
168
    }
169
170
    /// Sets the minimum parent-space margin around the panel.
171
    pub const fn margin(mut self, margin: Size) -> Self {
172
        self.margin = margin;
173
        self
174
    }
175
176
    /// Returns the largest panel size available inside `area`.
177
    fn available_max(&self, area: Rect) -> Size {
178
        Size::new(
179
            self.max_size
180
                .cols
181
                .min(area.cols.saturating_sub(self.margin.cols.saturating_mul(2))),
182
            self.max_size
183
                .rows
184
                .min(area.rows.saturating_sub(self.margin.rows.saturating_mul(2))),
185
        )
186
    }
187
188
    /// Returns the dialog size under `max`.
189
    fn panel_size(&self, max: Size) -> Size {
190
        let action = self.action_line();
191
        let body_width = self.body.iter().map(Line::width).max().unwrap_or_default();
192
        let content_width = self.heading.width().max(body_width).max(action.width());
193
        let content_rows = 1
194
            + usize::from(!self.body.is_empty() || !self.actions.items().is_empty())
195
            + self.body.len()
196
            + if self.actions.items().is_empty() {
197
                0
198
            } else {
199
                2
200
            };
201
        let size = Size::new(
202
            content_width
203
                .saturating_add(DIALOG_PADDING.saturating_mul(2))
204
                .saturating_add(2),
205
            content_rows.saturating_add(2),
206
        );
207
        let min = Size::new(2.min(max.cols), 2.min(max.rows));
208
209
        size.constrain(Constraint::new(min, max))
210
    }
211
212
    /// Returns the rendered action line.
213
    fn action_line(&self) -> Line {
214
        self.kind.action_bar(self.actions.clone()).line()
215
    }
216
217
    /// Renders the dialog heading.
218
    fn render_heading(&self, area: Rect, buf: &mut Buffer) {
219
        let heading = self.heading.clone().style(self.kind.heading_style());
220
        Line::renders([heading], area, buf);
221
    }
222
223
    /// Renders dialog body lines without entering the reserved action rows.
224
    fn render_body(&self, area: Rect, buf: &mut Buffer) {
225
        Line::renders(self.body.iter().take(area.rows).cloned(), area, buf);
226
    }
227
228
    /// Renders the action row at the bottom of the dialog.
229
    fn render_actions(&self, area: Rect, buf: &mut Buffer) {
230
        if self.actions.items().is_empty() {
231
            return;
232
        }
233
        Line::renders([self.action_line()], area, buf);
234
    }
235
}
236
237
impl Widget for Dialog {
238
    fn size(&self, parent: Constraint) -> Size {
239
        parent.bounded_size()
240
    }
241
242
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
243
        let max = self.available_max(area);
244
        let size = self.panel_size(max);
245
        let area = overlay_area(area, size, self.margin);
246
247
        if area.is_empty() {
248
            return;
249
        }
250
251
        buf.fill(area, self.background.clone());
252
        self.kind.border().draw(area, buf);
253
254
        let content = area.inner(1);
255
        let content_cols = content
256
            .cols
257
            .saturating_sub(DIALOG_PADDING.saturating_mul(2));
258
        let content_x = content.x + DIALOG_PADDING.min(content.cols);
259
        let heading_area = Rect::new(content_x, content.y, content_cols, 1);
260
        self.render_heading(heading_area, buf);
261
262
        let action_area = if self.actions.items().is_empty() || content.rows < 2 {
263
            Rect::ZERO
264
        } else {
265
            Rect::new(
266
                content_x,
267
                content.bottom().saturating_sub(1),
268
                content_cols,
269
                1,
270
            )
271
        };
272
        let body_y = content.y.saturating_add(2);
273
        let body_bottom = if action_area.is_empty() {
274
            content.bottom()
275
        } else {
276
            action_area.y.saturating_sub(1)
277
        };
278
        let body_area = Rect::new(
279
            content_x,
280
            body_y,
281
            content_cols,
282
            body_bottom.saturating_sub(body_y),
283
        );
284
285
        self.render_body(body_area, buf);
286
        self.render_actions(action_area, buf);
287
    }
288
}
289
290
#[cfg(test)]
291
mod tests {
292
    use super::*;
293
    use tui_core::{Buffer, Rect};
294
295
    #[test]
296
    fn error_dialog_uses_negative_chrome() {
297
        let mut dialog = Dialog::error()
298
            .body_line("State mismatch")
299
            .max_size(Size::new(24, 6))
300
            .margin(Size::MIN);
301
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
302
303
        dialog.render(buffer.area(), &mut buffer);
304
305
        assert!(first_position_with_foreground(&buffer, colors::rgb::NEGATIVE_LIGHT).is_some());
306
    }
307
308
    #[test]
309
    fn dialog_keeps_actions_visible_when_body_is_taller_than_panel() {
310
        let body = [
311
            Line::new("one"),
312
            Line::new("two"),
313
            Line::new("three"),
314
            Line::new("four"),
315
            Line::new("five"),
316
        ];
317
        let mut dialog = Dialog::error()
318
            .body(body)
319
            .actions(ActionList::new().action("r", "reset").action("q", "quit"))
320
            .max_size(Size::new(30, 7))
321
            .margin(Size::MIN);
322
        let mut buffer = Buffer::empty(Rect::new(0, 0, 34, 9));
323
324
        dialog.render(buffer.area(), &mut buffer);
325
326
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_some());
327
    }
328
329
    #[test]
330
    fn tiny_dialog_drops_actions_instead_of_overwriting_the_heading() {
331
        let mut dialog = Dialog::error()
332
            .actions(ActionList::new().action("q", "quit"))
333
            .max_size(Size::new(24, 3))
334
            .margin(Size::MIN);
335
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 3));
336
337
        dialog.render(buffer.area(), &mut buffer);
338
339
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_none());
340
    }
341
342
    #[test]
343
    fn error_dialog_actions_use_grey_pills_black_keys_and_lighter_labels() {
344
        let mut dialog = Dialog::error()
345
            .actions(ActionList::new().action("r", "reset"))
346
            .max_size(Size::new(24, 5))
347
            .margin(Size::MIN);
348
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
349
350
        dialog.render(buffer.area(), &mut buffer);
351
352
        let key = first_foreground_with_background(&buffer, Color::Fixed(250));
353
        let label = first_position_with_foreground(&buffer, Color::Fixed(244));
354
355
        assert_eq!(key, Some(Color::Black));
356
        assert!(label.is_some());
357
    }
358
359
    /// Returns the first position whose foreground color is `foreground`.
360
    fn first_position_with_foreground(
361
        buffer: &Buffer,
362
        foreground: Color,
363
    ) -> Option<(usize, usize)> {
364
        for y in 0..buffer.area().rows {
365
            for x in 0..buffer.area().cols {
366
                let Some(cell) = buffer.get(x, y) else {
367
                    continue;
368
                };
369
                if cell.style().fg_color() == foreground {
370
                    return Some((x, y));
371
                }
372
            }
373
        }
374
        None
375
    }
376
377
    /// Returns the first position whose background color is `background`.
378
    fn first_position_with_background(
379
        buffer: &Buffer,
380
        background: Color,
381
    ) -> Option<(usize, usize)> {
382
        for y in 0..buffer.area().rows {
383
            for x in 0..buffer.area().cols {
384
                let Some(cell) = buffer.get(x, y) else {
385
                    continue;
386
                };
387
                if cell.style().bg_color() == background {
388
                    return Some((x, y));
389
                }
390
            }
391
        }
392
        None
393
    }
394
395
    /// Returns the foreground color of the first cell with `background`.
396
    fn first_foreground_with_background(buffer: &Buffer, background: Color) -> Option<Color> {
397
        for y in 0..buffer.area().rows {
398
            for x in 0..buffer.area().cols {
399
                let Some(cell) = buffer.get(x, y) else {
400
                    continue;
401
                };
402
                if cell.style().bg_color() == background {
403
                    return Some(cell.style().fg_color());
404
                }
405
            }
406
        }
407
        None
408
    }
409
}