1
//! The buttons each kind of modal offers and the intent each one presses.
2

            
3
use super::Modal;
4
use crate::event::{BuilderKey, Intent};
5

            
6
/// A button label with `~X~` hotkey marks, and what pressing it does.
7
pub type Spec = (&'static str, Intent);
8

            
9
const APPLY_CLOSE: [Spec; 2] = [
10
    ("A~p~ply", Intent::Builder(BuilderKey::Apply)),
11
    ("~C~lose", Intent::CloseTopmost),
12
];
13
const YES_NO: [Spec; 2] = [
14
    ("~Y~es", Intent::ConfirmYes),
15
    ("~N~o", Intent::CloseTopmost),
16
];
17
const CLOSE: [Spec; 1] = [("~C~lose", Intent::CloseTopmost)];
18

            
19
impl Modal {
20
    /// The button Enter and Space press: the focused one, else the one that submits, else the
21
    /// only one.
22
    #[must_use]
23
766
    pub fn press_button(&self) -> Option<usize> {
24
766
        self.focused_button()
25
300
            .or_else(|| {
26
300
                self.button_specs()
27
300
                    .iter()
28
300
                    .position(|&(_, intent)| intent == Intent::Submit)
29
300
            })
30
53
            .or_else(|| (self.button_specs().len() == 1).then_some(0))
31
766
    }
32

            
33
    /// What Enter and Space do: the intent of [`Modal::press_button`], else a submit.
34
    #[must_use]
35
694
    pub fn press_intent(&self) -> Intent {
36
694
        let spec = self
37
694
            .press_button()
38
694
            .and_then(|at| self.button_specs().get(at));
39
694
        spec.map_or(Intent::Submit, |&(_, intent)| intent)
40
694
    }
41

            
42
    /// The button of each choice this modal offers, with the intent it presses.
43
    #[must_use]
44
7493
    pub fn button_specs(&self) -> &'static [Spec] {
45
7493
        match self {
46
4846
            Modal::Form(form) => form.buttons(),
47
127
            Modal::FilterBuilder(_) => &APPLY_CLOSE,
48
2155
            Modal::Confirm { .. } => &YES_NO,
49
365
            Modal::Csv(_) | Modal::Draft(_) => &CLOSE,
50
        }
51
7493
    }
52
}