1
//! Overlay rendering: Confirm and Form bodies.
2

            
3
use super::canvas::{Offscreen, draw_placed};
4
use super::form::{FormBody, draw_form, form_body};
5
use super::{body_area, draw_panel, filter_builder};
6
use crate::app::{App, PendingForm};
7
use crate::event::Intent;
8
use crate::focus::{FocusTarget, current_focus};
9
use crate::form::Form;
10
use crate::hits::{Hits, Slot, Surface, Target};
11
use crate::keymap::{self, KeyView};
12
use crate::modal::Modal;
13
use crate::overlay::{Layer, Placement};
14
use ratatui::Frame;
15
use ratatui::layout::Rect;
16
use ratatui::text::{Line, Text};
17
use ratatui::widgets::{Paragraph, Wrap};
18
use tvui::{Button, ButtonRow, Dialog, scrollbar_parts};
19

            
20
/// The intent Enter presses in `modal`; the confirm prompt's default answer is resolved.
21
692
fn enter_intent(modal: &Modal, keys: &KeyView<'_>) -> Option<Intent> {
22
692
    match keys.bound("Enter")? {
23
487
        Intent::Press => Some(modal.press_intent()),
24
180
        intent => Some(intent),
25
    }
26
692
}
27

            
28
/// The buttons of `modal`; the default is the one Enter presses.
29
692
pub(super) fn buttons(modal: &Modal, app: &App) -> Vec<Button<'static>> {
30
692
    let default = enter_intent(modal, &keymap::in_modal(app, modal));
31
692
    modal
32
692
        .button_specs()
33
692
        .iter()
34
        .map(|&(label, intent)| Button {
35
1344
            label,
36
1344
            default: Some(intent) == default,
37
1344
        })
38
        .collect()
39
692
}
40

            
41
/// The buttons of `layer`; a layer below the top has no default.
42
685
fn layer_buttons(layer: Layer<'_>, app: &App) -> Vec<Button<'static>> {
43
685
    let mut buttons = buttons(layer.modal, app);
44
685
    if !layer.top {
45
32
        buttons.iter_mut().for_each(|button| button.default = false);
46
669
    }
47
685
    buttons
48
685
}
49

            
50
685
pub(super) fn draw_modal(
51
685
    frame: &mut Frame,
52
685
    full: Rect,
53
685
    layer: Layer<'_>,
54
685
    app: &App,
55
685
    hits: &mut Hits,
56
685
) {
57
685
    let host = body_area(full);
58
685
    match layer.modal {
59
436
        Modal::Form(form) => draw_form_modal(frame, host, layer, form, app, hits),
60
249
        _ => draw_text_modal(frame, host, layer, app, hits),
61
    }
62
685
}
63

            
64
/// Draws a dialog that opens at `auto`, where it was moved or sized to since, with `draw`.
65
689
fn place_dialog(
66
689
    frame: &mut Frame,
67
689
    (host, auto, min): (Rect, Rect, (u16, u16)),
68
689
    (placement, top): (Placement, bool),
69
689
    hits: &mut Hits,
70
689
    draw: impl FnOnce(&mut Offscreen, Rect, &mut Hits),
71
689
) {
72
689
    if top {
73
669
        hits.set_dialog(Slot { auto, min, host });
74
20
    }
75
689
    let place = placement.place(auto, min, host);
76
689
    draw_placed(frame, place, host, hits, |canvas, area, hits| {
77
689
        record_frame(hits, area);
78
689
        draw(canvas, area, hits);
79
689
    });
80
689
}
81

            
82
/// The top row of a dialog, which a press drags, and its `[■]`, which a release closes.
83
689
fn record_frame(hits: &mut Hits, area: Rect) {
84
689
    hits.push(Rect { height: 1, ..area }, Target::Title);
85
689
    if let Some(close) = Dialog::close_area(area) {
86
689
        hits.push(close, Target::Close);
87
    }
88
689
}
89

            
90
436
fn draw_form_modal(
91
436
    frame: &mut Frame,
92
436
    host: Rect,
93
436
    layer: Layer<'_>,
94
436
    form: &Form,
95
436
    app: &App,
96
436
    hits: &mut Hits,
97
436
) {
98
436
    let body = form_body(form, (false, layer.top), app);
99
436
    let buttons = layer_buttons(layer, app);
100
436
    let (auto, min) = form_slot(&body, &buttons, host);
101
436
    let focused = current_focus(app) == FocusTarget::Overlay || app.dragging_layer();
102
436
    let with_cursor = layer.top && focused;
103
436
    place_dialog(
104
436
        frame,
105
436
        (host, auto, min),
106
436
        (layer.placement, layer.top),
107
436
        hits,
108
436
        |canvas, area, hits| {
109
436
            draw_form(canvas, area, &body, &buttons, &app.theme, with_cursor, hits);
110
436
        },
111
    );
112
436
}
113

            
114
/// Where a form dialog opens and the least it is sized to.
115
440
fn form_slot(body: &FormBody<'_>, buttons: &[Button<'_>], host: Rect) -> (Rect, (u16, u16)) {
116
440
    let size = (body.widest(), body.height());
117
440
    let auto = Dialog::fitted(size, buttons, ButtonRow::BottomRight, host);
118
440
    (auto, Dialog::min_size(buttons, ButtonRow::BottomRight))
119
440
}
120

            
121
/// The locked form of a submitted request, where its dialog stood.
122
4
pub(super) fn draw_pending(frame: &mut Frame, full: Rect, pending: &PendingForm, app: &App) {
123
4
    let host = body_area(full);
124
4
    let sizing = form_body(&pending.form, (false, true), app);
125
4
    let buttons: Vec<Button> = pending
126
4
        .form
127
4
        .buttons()
128
4
        .iter()
129
        .map(|&(label, _)| Button {
130
8
            label,
131
8
            default: false,
132
8
        })
133
        .collect();
134
4
    let (auto, min) = form_slot(&sizing, &buttons, host);
135
4
    let body = form_body(&pending.form, (true, true), app);
136
4
    place_dialog(
137
4
        frame,
138
4
        (host, auto, min),
139
4
        (pending.form.placement, false),
140
4
        &mut Hits::default(),
141
4
        |canvas, area, hits| {
142
4
            draw_form(canvas, area, &body, &buttons, &app.theme, false, hits);
143
4
        },
144
    );
145
4
}
146

            
147
249
fn draw_text_modal(frame: &mut Frame, host: Rect, layer: Layer<'_>, app: &App, hits: &mut Hits) {
148
249
    let modal = layer.modal;
149
249
    let Some((title, body, focus)) = modal_content(modal, app) else {
150
        return;
151
    };
152
249
    let buttons = layer_buttons(layer, app);
153
249
    let (auto, min) = match modal {
154
        Modal::Confirm { .. } => {
155
201
            let text_len = body.lines.iter().map(Line::width).sum();
156
201
            let auto = Dialog::message_box(text_len, &buttons, host);
157
201
            (auto, (auto.width, auto.height))
158
        }
159
48
        _ => (
160
48
            fitted_rect(&body, &buttons, host),
161
48
            Dialog::min_size(&buttons, ButtonRow::Centred),
162
48
        ),
163
    };
164
249
    place_dialog(
165
249
        frame,
166
249
        (host, auto, min),
167
249
        (layer.placement, layer.top),
168
249
        hits,
169
249
        |canvas, area, hits| {
170
249
            let content = (title.as_str(), body, focus);
171
249
            paint_text(canvas, area, layer, (&buttons, app), content, hits);
172
249
        },
173
    );
174
249
}
175

            
176
249
fn paint_text(
177
249
    canvas: &mut Offscreen,
178
249
    area: Rect,
179
249
    layer: Layer<'_>,
180
249
    (buttons, app): (&[Button<'_>], &App),
181
249
    (title, body, focus): (&str, Text<'static>, usize),
182
249
    hits: &mut Hits,
183
249
) {
184
249
    let (rows, view) = (
185
249
        body.lines.len(),
186
249
        usize::from(Dialog::body_area(area).height),
187
249
    );
188
249
    let modal = layer.modal;
189
249
    let top = match modal {
190
2
        Modal::FilterBuilder(_) => usize::from(keep_visible(focus, area.height)),
191
41
        Modal::Draft(help) => help.scroll.fit(rows, view),
192
5
        Modal::Csv(csv) => csv.scroll.fit(rows, view),
193
201
        _ => 0,
194
    };
195
249
    let dialog = Dialog::new(&app.theme, title, buttons)
196
249
        .focused(modal.focused_button().filter(|_| layer.top))
197
249
        .pressed(app.pressed_button().filter(|_| layer.top))
198
249
        .dragging(app.dragging_layer() && layer.top)
199
249
        .inactive(!layer.top);
200
249
    let dialog = match modal {
201
201
        Modal::Confirm { .. } => dialog,
202
48
        _ => dialog.scrollbar(rows, view, top),
203
    };
204
249
    draw_panel(
205
249
        canvas,
206
249
        area,
207
249
        dialog,
208
249
        message_or_body(modal, body, area, top),
209
249
    );
210
249
    if modal.scrolls() {
211
46
        record_body(hits, area, (rows, view, top));
212
203
    }
213
249
    record_buttons(hits, area, buttons, ButtonRow::Centred);
214
249
}
215

            
216
/// The text of `modal` and where it goes: a confirmation wraps in the Turbo Vision message
217
/// area, the rest scroll in the body.
218
249
fn message_or_body(
219
249
    modal: &Modal,
220
249
    body: Text<'static>,
221
249
    area: Rect,
222
249
    top: usize,
223
249
) -> (Paragraph<'static>, Rect) {
224
249
    match modal {
225
201
        Modal::Confirm { .. } => (
226
201
            Paragraph::new(body).wrap(Wrap { trim: false }),
227
201
            Dialog::message_area(area),
228
201
        ),
229
48
        _ => (
230
48
            Paragraph::new(body).scroll((u16::try_from(top).unwrap_or(u16::MAX), 0)),
231
48
            Dialog::body_area(area),
232
48
        ),
233
    }
234
249
}
235

            
236
/// The body of a scrolled overlay and the parts of its scrollbar.
237
46
fn record_body(hits: &mut Hits, area: Rect, dims: (usize, usize, usize)) {
238
46
    hits.push(Dialog::body_area(area), Target::Body(Surface::Modal));
239
46
    for (rect, part) in scrollbar_parts(Dialog::scrollbar_frame(area), dims) {
240
136
        hits.push(rect, Target::Scroll(Surface::Modal, part));
241
    }
242
46
}
243

            
244
705
pub(super) fn record_buttons(hits: &mut Hits, area: Rect, buttons: &[Button<'_>], row: ButtonRow) {
245
705
    for (index, rect) in Dialog::button_areas(area, buttons, row)
246
705
        .into_iter()
247
705
        .enumerate()
248
    {
249
1341
        hits.push(Button::face(rect), Target::Button(index));
250
    }
251
705
}
252

            
253
/// A box around `body` and the button row, as tall as its lines, centred.
254
52
fn fitted_rect(body: &Text<'_>, buttons: &[Button<'_>], full: Rect) -> Rect {
255
52
    let widest = body.lines.iter().map(Line::width).max().unwrap_or(0);
256
52
    Dialog::fitted(
257
52
        (widest, body.lines.len()),
258
52
        buttons,
259
52
        ButtonRow::Centred,
260
52
        full,
261
52
    )
262
52
}
263

            
264
/// The scroll that keeps `line` inside the body of a dialog `height` rows tall.
265
2
fn keep_visible(line: usize, height: u16) -> u16 {
266
2
    scroll_to(line, height.saturating_sub(2 + Dialog::BUTTON_ROWS))
267
2
}
268

            
269
/// The scroll that keeps `line` inside `rows` rows.
270
530
pub(super) fn scroll_to(line: usize, rows: u16) -> u16 {
271
530
    u16::try_from((line + 1).saturating_sub(usize::from(rows))).unwrap_or(u16::MAX)
272
530
}
273

            
274
/// The title, the body and the line of the body the focus is on; a form draws itself.
275
252
fn modal_content(modal: &Modal, app: &App) -> Option<(String, Text<'static>, usize)> {
276
48
    let text = |title: &str, lines: &[String]| (title.to_string(), Text::from(lines.join("\n")), 0);
277
252
    Some(match modal {
278
6
        Modal::Csv(csv) => text("Category CSV (saving is local only)", &csv.lines),
279
42
        Modal::Draft(draft) => text("Template draft", &draft.lines),
280
        Modal::FilterBuilder(builder) => {
281
3
            let (body, focus) = filter_builder::content(builder, &app.theme);
282
3
            ("Filter".to_string(), body, focus)
283
        }
284
201
        Modal::Confirm { prompt, .. } => ("Confirm".to_string(), Text::from(prompt.clone()), 0),
285
        Modal::Form(_) => return None,
286
    })
287
252
}
288

            
289
#[cfg(test)]
290
mod tests;