Skip to main content

tui/modal/
buttons.rs

1//! The buttons each kind of modal offers and the intent each one presses.
2
3use super::Modal;
4use crate::event::{BuilderKey, Intent};
5
6/// A button label with `~X~` hotkey marks, and what pressing it does.
7pub type Spec = (&'static str, Intent);
8
9const APPLY_CLOSE: [Spec; 2] = [
10    ("A~p~ply", Intent::Builder(BuilderKey::Apply)),
11    ("~C~lose", Intent::CloseTopmost),
12];
13const YES_NO: [Spec; 2] = [
14    ("~Y~es", Intent::ConfirmYes),
15    ("~N~o", Intent::CloseTopmost),
16];
17const CLOSE: [Spec; 1] = [("~C~lose", Intent::CloseTopmost)];
18
19impl 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    pub fn press_button(&self) -> Option<usize> {
24        self.focused_button()
25            .or_else(|| {
26                self.button_specs()
27                    .iter()
28                    .position(|&(_, intent)| intent == Intent::Submit)
29            })
30            .or_else(|| (self.button_specs().len() == 1).then_some(0))
31    }
32
33    /// What Enter and Space do: the intent of [`Modal::press_button`], else a submit.
34    #[must_use]
35    pub fn press_intent(&self) -> Intent {
36        let spec = self
37            .press_button()
38            .and_then(|at| self.button_specs().get(at));
39        spec.map_or(Intent::Submit, |&(_, intent)| intent)
40    }
41
42    /// The button of each choice this modal offers, with the intent it presses.
43    #[must_use]
44    pub fn button_specs(&self) -> &'static [Spec] {
45        match self {
46            Modal::Form(form) => form.buttons(),
47            Modal::FilterBuilder(_) => &APPLY_CLOSE,
48            Modal::Confirm { .. } => &YES_NO,
49            Modal::Csv(_) | Modal::Draft(_) => &CLOSE,
50        }
51    }
52}