1
//! Actions of the topmost overlay: close, confirm and submit.
2

            
3
use super::submit::{execute_confirm, submit_form};
4
use crate::app::App;
5
use crate::form::FormKind;
6
use crate::modal::{ConfirmAction, Modal};
7
use crate::widgets::WidgetKind;
8

            
9
/// Esc closes an open split tag list first, else the overlay.
10
99
pub(super) fn close_topmost(app: &mut App) {
11
99
    if let Some(Modal::Form(form)) = app.overlays.top_mut()
12
35
        && form.close_tags()
13
    {
14
1
        return;
15
98
    }
16
98
    if matches!(app.overlays.top(), Some(Modal::Form(form)) if form.kind == FormKind::Options) {
17
5
        return app.cancel_options();
18
93
    }
19
93
    if app.overlays.top().is_some_and(Modal::is_dirty) {
20
12
        app.overlays.push(Modal::confirm(
21
12
            "Discard changes?",
22
12
            ConfirmAction::DiscardForm,
23
12
        ));
24
12
        return;
25
81
    }
26
81
    app.overlays.pop();
27
99
}
28

            
29
/// Confirm the topmost overlay, but only when it is a `Modal::Confirm`.
30
71
pub(super) fn confirm_topmost(app: &mut App) {
31
71
    if !matches!(app.overlays.top(), Some(Modal::Confirm { .. })) {
32
1
        return;
33
70
    }
34
70
    act_on_top(app, |app, modal| {
35
70
        if let Modal::Confirm { action, .. } = modal {
36
70
            execute_confirm(app, action);
37
        }
38
70
    });
39
71
}
40

            
41
/// Pops the topmost overlay for `act`, during which its window still counts as the dialog's.
42
276
fn act_on_top(app: &mut App, act: impl FnOnce(&mut App, Modal)) {
43
276
    let origin = app.overlays.origin();
44
276
    let Some(modal) = app.overlays.pop() else {
45
        return;
46
    };
47
276
    app.overlays.set_origin(origin);
48
276
    act(app, modal);
49
276
    app.overlays.release();
50
276
}
51

            
52
/// Whether the topmost overlay is a template form.
53
2329
pub(super) fn template_form_open(app: &App) -> bool {
54
2329
    matches!(app.overlays.top(), Some(Modal::Form(form)) if form.is_template())
55
2329
}
56

            
57
/// Whether C-t does something: it tests a template form, or opens the focused split's tags.
58
1736
pub(super) fn toggles_split_tags(app: &App) -> bool {
59
1736
    template_form_open(app)
60
1727
        || matches!(app.overlays.top(), Some(Modal::Form(form))
61
1627
            if form.focused_widget_kind() == Some(WidgetKind::Splits))
62
1736
}
63

            
64
/// Apply Enter to the topmost overlay (form submit or confirm action).
65
206
pub(super) fn submit_modal(app: &mut App) {
66
206
    act_on_top(app, |app, modal| match modal {
67
        Modal::Confirm { action, .. } => execute_confirm(app, action),
68
206
        Modal::Form(form) => submit_form(app, form),
69
        Modal::Csv(_) | Modal::Draft(_) | Modal::FilterBuilder(_) => {}
70
206
    });
71
206
}