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
53impl Action {
54    /// Default tree view action map.
55    pub fn defaults() -> Actions {
56        [
57            (Event::Key(Key::Home), Self::SelectTop),
58            (Event::Key(Key::Up), Self::SelectUp),
59            (Event::Key(Key::PageUp), Self::SelectUpPage),
60            (Event::Key(Key::End), Self::SelectBottom),
61            (Event::Key(Key::Down), Self::SelectDown),
62            (Event::Key(Key::PageDown), Self::SelectDownPage),
63            (Event::Key(Key::Right), Self::Expand),
64            (Event::Char('+'), Self::ExpandRecursive),
65            (Event::Char('>'), Self::ExpandAll),
66            (Event::Key(Key::Left), Self::Collapse),
67            (Event::Char('-'), Self::CollapseRecursive),
68            (Event::Char('<'), Self::CollapseAll),
69            (Event::Key(Key::Enter), Self::ToggleState),
70        ]
71        .into()
72    }
73
74    /// Remove from action map.
75    ///
76    /// Return true if removed.
77    pub fn remove(&self, actions: &mut Actions) -> bool {
78        let events = self.events(actions);
79        for event in &events {
80            actions.remove(event);
81        }
82        !events.is_empty()
83    }
84
85    /// Events for the action.
86    pub fn events(&self, actions: &Actions) -> Vec<Event> {
87        actions
88            .into_iter()
89            .filter_map(|(event, action)| if action == self { Some(event.clone()) } else { None })
90            .collect()
91    }
92}