crates/tui-widgets/src/dialog.rs 15.5 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 effective margin, dropping it when compact content needs the space.
177
    fn effective_margin(&self, area: Rect) -> Size {
178
        Size::new(
179
            if area.cols >= self.margin.cols.saturating_mul(2).saturating_add(2) {
180
                self.margin.cols
181
            } else {
182
                0
183
            },
184
            if area.rows >= self.margin.rows.saturating_mul(2).saturating_add(5) {
185
                self.margin.rows
186
            } else {
187
                0
188
            },
189
        )
190
    }
191
192
    /// Returns the largest panel size available inside `area` and `margin`.
193
    fn available_max(&self, area: Rect, margin: Size) -> Size {
194
        Size::new(
195
            self.max_size
196
                .cols
197
                .min(area.cols.saturating_sub(margin.cols.saturating_mul(2))),
198
            self.max_size
199
                .rows
200
                .min(area.rows.saturating_sub(margin.rows.saturating_mul(2))),
201
        )
202
    }
203
204
    /// Returns the dialog's natural content height.
205
    fn content_rows(&self) -> usize {
206
        1 + usize::from(!self.body.is_empty() || !self.actions.items().is_empty())
207
            + self.body.len()
208
            + if self.actions.items().is_empty() {
209
                0
210
            } else {
211
                2
212
            }
213
    }
214
215
    /// Returns the dialog size under `max`.
216
    fn panel_size(&self, max: Size) -> Size {
217
        let action = self.action_line();
218
        let body_width = self.body.iter().map(Line::width).max().unwrap_or_default();
219
        let content_width = self.heading.width().max(body_width).max(action.width());
220
        let content_rows = self.content_rows();
221
        let size = Size::new(
222
            content_width
223
                .saturating_add(DIALOG_PADDING.saturating_mul(2))
224
                .saturating_add(2),
225
            content_rows.saturating_add(2),
226
        );
227
        let min = Size::new(2.min(max.cols), 2.min(max.rows));
228
229
        size.constrain(Constraint::new(min, max))
230
    }
231
232
    /// Returns the rendered action line.
233
    fn action_line(&self) -> Line {
234
        self.kind.action_bar(self.actions.clone()).line()
235
    }
236
237
    /// Renders the dialog heading.
238
    fn render_heading(&self, area: Rect, buf: &mut Buffer) {
239
        let heading = self.heading.clone().style(self.kind.heading_style());
240
        Line::renders([heading], area, buf);
241
    }
242
243
    /// Renders dialog body lines without entering the reserved action rows.
244
    fn render_body(&self, area: Rect, buf: &mut Buffer) {
245
        Line::renders(self.body.iter().take(area.rows).cloned(), area, buf);
246
    }
247
248
    /// Renders the action row at the bottom of the dialog.
249
    fn render_actions(&self, area: Rect, buf: &mut Buffer) {
250
        if self.actions.items().is_empty() {
251
            return;
252
        }
253
        Line::renders([self.action_line()], area, buf);
254
    }
255
}
256
257
impl Widget for Dialog {
258
    fn size(&self, parent: Constraint) -> Size {
259
        parent.bounded_size()
260
    }
261
262
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
263
        let margin = self.effective_margin(area);
264
        let max = self.available_max(area, margin);
265
        let size = self.panel_size(max);
266
        let area = overlay_area(area, size, margin);
267
268
        if area.is_empty() {
269
            return;
270
        }
271
272
        buf.fill(area, self.background.clone());
273
        self.kind.border().draw(area, buf);
274
275
        let content = area.inner(1);
276
        let content_cols = content
277
            .cols
278
            .saturating_sub(DIALOG_PADDING.saturating_mul(2));
279
        let content_x = content.x + DIALOG_PADDING.min(content.cols);
280
        let heading_area = Rect::new(content_x, content.y, content_cols, 1);
281
        self.render_heading(heading_area, buf);
282
283
        let compact = content.rows < self.content_rows();
284
        let action_area = if self.actions.items().is_empty() || content.rows < 2 {
285
            Rect::ZERO
286
        } else {
287
            Rect::new(
288
                content_x,
289
                content.bottom().saturating_sub(1),
290
                content_cols,
291
                1,
292
            )
293
        };
294
        let body_y = content.y.saturating_add(if compact { 1 } else { 2 });
295
        let body_bottom = if action_area.is_empty() {
296
            content.bottom()
297
        } else {
298
            action_area.y.saturating_sub(usize::from(!compact))
299
        };
300
        let body_area = Rect::new(
301
            content_x,
302
            body_y,
303
            content_cols,
304
            body_bottom.saturating_sub(body_y),
305
        );
306
307
        self.render_body(body_area, buf);
308
        self.render_actions(action_area, buf);
309
    }
310
}
311
312
#[cfg(test)]
313
mod tests {
314
    use super::*;
315
    use tui_core::{Buffer, Rect};
316
317
    #[test]
318
    fn error_dialog_uses_negative_chrome() {
319
        let mut dialog = Dialog::error()
320
            .body_line("State mismatch")
321
            .max_size(Size::new(24, 6))
322
            .margin(Size::MIN);
323
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
324
325
        dialog.render(buffer.area(), &mut buffer);
326
327
        assert!(first_position_with_foreground(&buffer, colors::rgb::NEGATIVE_LIGHT).is_some());
328
    }
329
330
    #[test]
331
    fn dialog_keeps_actions_visible_when_body_is_taller_than_panel() {
332
        let body = [
333
            Line::new("one"),
334
            Line::new("two"),
335
            Line::new("three"),
336
            Line::new("four"),
337
            Line::new("five"),
338
        ];
339
        let mut dialog = Dialog::error()
340
            .body(body)
341
            .actions(ActionList::new().action("r", "reset").action("q", "quit"))
342
            .max_size(Size::new(30, 7))
343
            .margin(Size::MIN);
344
        let mut buffer = Buffer::empty(Rect::new(0, 0, 34, 9));
345
346
        dialog.render(buffer.area(), &mut buffer);
347
348
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_some());
349
    }
350
351
    #[test]
352
    fn compact_dialog_keeps_body_and_actions_visible() {
353
        let mut dialog = Dialog::error()
354
            .body_line("The existing review is stale.")
355
            .actions(
356
                ActionList::new()
357
                    .action("enter", "rebase")
358
                    .action("x", "reset")
359
                    .action("esc", "quit"),
360
            );
361
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 5));
362
363
        dialog.render(buffer.area(), &mut buffer);
364
365
        let text = buffer_text(&buffer);
366
        assert!(
367
            text.contains("The existing review is stale."),
368
            "text: {text:?}"
369
        );
370
        assert!(text.contains("rebase"), "text: {text:?}");
371
        assert!(text.contains("reset"), "text: {text:?}");
372
        assert!(text.contains("quit"), "text: {text:?}");
373
    }
374
375
    #[test]
376
    fn capped_dialog_keeps_complete_body_visible() {
377
        let mut dialog = Dialog::error()
378
            .body([
379
                Line::new("The existing review is stale."),
380
                Line::new("Its resolved commits no longer match this branch."),
381
                Line::blank(),
382
                Line::new("Rebasing carries matching accepted hunks forward."),
383
                Line::new("Changed or new hunks are left for review."),
384
            ])
385
            .actions(
386
                ActionList::new()
387
                    .action("enter", "rebase")
388
                    .action("x", "reset")
389
                    .action("esc", "quit"),
390
            )
391
            .max_size(Size::new(78, 10));
392
        let mut buffer = Buffer::empty(Rect::new(0, 0, 80, 12));
393
394
        dialog.render(buffer.area(), &mut buffer);
395
396
        let text = buffer_text(&buffer);
397
        assert!(
398
            text.contains("Changed or new hunks are left for review."),
399
            "text: {text:?}"
400
        );
401
        assert!(text.contains("rebase"), "text: {text:?}");
402
        assert!(text.contains("reset"), "text: {text:?}");
403
        assert!(text.contains("quit"), "text: {text:?}");
404
    }
405
    #[test]
406
    fn tiny_dialog_drops_actions_instead_of_overwriting_the_heading() {
407
        let mut dialog = Dialog::error()
408
            .actions(ActionList::new().action("q", "quit"))
409
            .max_size(Size::new(24, 3))
410
            .margin(Size::MIN);
411
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 3));
412
413
        dialog.render(buffer.area(), &mut buffer);
414
415
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_none());
416
    }
417
418
    #[test]
419
    fn error_dialog_actions_use_grey_pills_black_keys_and_lighter_labels() {
420
        let mut dialog = Dialog::error()
421
            .actions(ActionList::new().action("r", "reset"))
422
            .max_size(Size::new(24, 5))
423
            .margin(Size::MIN);
424
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
425
426
        dialog.render(buffer.area(), &mut buffer);
427
428
        let key = first_foreground_with_background(&buffer, Color::Fixed(250));
429
        let label = first_position_with_foreground(&buffer, Color::Fixed(244));
430
431
        assert_eq!(key, Some(Color::Black));
432
        assert!(label.is_some());
433
    }
434
435
    /// Returns all visible buffer cells as newline-separated text.
436
    fn buffer_text(buffer: &Buffer) -> String {
437
        let mut text = String::new();
438
        for y in 0..buffer.area().rows {
439
            for x in 0..buffer.area().cols {
440
                if let Some(cell) = buffer.get(x, y) {
441
                    text.push_str(&cell.glyph());
442
                }
443
            }
444
            text.push('\n');
445
        }
446
        text
447
    }
448
449
    /// Returns the first position whose foreground color is `foreground`.
450
    fn first_position_with_foreground(
451
        buffer: &Buffer,
452
        foreground: Color,
453
    ) -> Option<(usize, usize)> {
454
        for y in 0..buffer.area().rows {
455
            for x in 0..buffer.area().cols {
456
                let Some(cell) = buffer.get(x, y) else {
457
                    continue;
458
                };
459
                if cell.style().fg_color() == foreground {
460
                    return Some((x, y));
461
                }
462
            }
463
        }
464
        None
465
    }
466
467
    /// Returns the first position whose background color is `background`.
468
    fn first_position_with_background(
469
        buffer: &Buffer,
470
        background: Color,
471
    ) -> Option<(usize, usize)> {
472
        for y in 0..buffer.area().rows {
473
            for x in 0..buffer.area().cols {
474
                let Some(cell) = buffer.get(x, y) else {
475
                    continue;
476
                };
477
                if cell.style().bg_color() == background {
478
                    return Some((x, y));
479
                }
480
            }
481
        }
482
        None
483
    }
484
485
    /// Returns the foreground color of the first cell with `background`.
486
    fn first_foreground_with_background(buffer: &Buffer, background: Color) -> Option<Color> {
487
        for y in 0..buffer.area().rows {
488
            for x in 0..buffer.area().cols {
489
                let Some(cell) = buffer.get(x, y) else {
490
                    continue;
491
                };
492
                if cell.style().bg_color() == background {
493
                    return Some(cell.style().fg_color());
494
                }
495
            }
496
        }
497
        None
498
    }
499
}