Skip to main content

cursive_tree/view/
actions.rs

1use {cursive::event::*, std::collections::*};
2
3/// Tree view action map.
4pub type Actions = HashMap<Event, Action>;
5
6//
7// Action
8//
9
10/// Tree view action.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum Action {
13    /// Select top row.
14    SelectTop,
15
16    /// Move selection up by one row.
17    SelectUp,
18
19    /// Move selection up by one page.
20    SelectUpPage,
21
22    /// Select bottom row.
23    SelectBottom,
24
25    /// Move selection down by one row.
26    SelectDown,
27
28    /// Move selection down by one page.
29    SelectDownPage,
30
31    /// Expand selected node.
32    Expand,
33
34    /// Expand selected node and all children recursively.
35    ExpandRecursive,
36
37    /// Expand all nodes.
38    ExpandAll,
39
40    /// Collapse selected node.
41    Collapse,
42
43    /// Collapse selected node and all children recursively.
44    CollapseRecursive,
45
46    /// Collapse all nodes.
47    CollapseAll,
48
49    /// Toggle selected node's collapse/expand state.
50    ToggleState,
51
52    /// Toggle debug mode.
53    ///
54    /// Intended for debugging.
55    ToggleDebug,
56}
57
58impl Action {
59    /// Default tree view action map.
60    pub fn defaults() -> Actions {
61        [
62            (Event::Key(Key::Home), Self::SelectTop),
63            (Event::Key(Key::Up), Self::SelectUp),
64            (Event::Key(Key::PageUp), Self::SelectUpPage),
65            (Event::Key(Key::End), Self::SelectBottom),
66            (Event::Key(Key::Down), Self::SelectDown),
67            (Event::Key(Key::PageDown), Self::SelectDownPage),
68            (Event::Key(Key::Right), Self::Expand),
69            (Event::Char('+'), Self::ExpandRecursive),
70            (Event::Char('>'), Self::ExpandAll),
71            (Event::Key(Key::Left), Self::Collapse),
72            (Event::Char('-'), Self::CollapseRecursive),
73            (Event::Char('<'), Self::CollapseAll),
74            (Event::Key(Key::Enter), Self::ToggleState),
75        ]
76        .into()
77    }
78
79    /// Remove from action map.
80    ///
81    /// Return true if removed.
82    pub fn remove(&self, actions: &mut Actions) -> bool {
83        let events = self.events(actions);
84        for event in &events {
85            actions.remove(event);
86        }
87        !events.is_empty()
88    }
89
90    /// Events for the action.
91    pub fn events(&self, actions: &Actions) -> Vec<Event> {
92        actions
93            .into_iter()
94            .filter_map(|(event, action)| if action == self { Some(event.clone()) } else { None })
95            .collect()
96    }
97}