cursive-tree 0.0.9

Tree view for the Cursive TUI library
Documentation
use {cursive::event::*, std::collections::*};

/// Tree view action map.
pub type Actions = HashMap<Event, Action>;

//
// Action
//

/// Tree view action.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Action {
    /// Select top row.
    SelectTop,

    /// Move selection up by one row.
    SelectUp,

    /// Move selection up by one page.
    SelectUpPage,

    /// Select bottom row.
    SelectBottom,

    /// Move selection down by one row.
    SelectDown,

    /// Move selection down by one page.
    SelectDownPage,

    /// Expand selected node.
    Expand,

    /// Expand selected node and all children recursively.
    ExpandRecursive,

    /// Expand all nodes.
    ExpandAll,

    /// Collapse selected node.
    Collapse,

    /// Collapse selected node and all children recursively.
    CollapseRecursive,

    /// Collapse all nodes.
    CollapseAll,

    /// Toggle selected node's collapse/expand state.
    ToggleState,

    /// Toggle debug mode.
    ///
    /// Intended for debugging.
    ToggleDebug,
}

impl Action {
    /// Default tree view action map.
    pub fn defaults() -> Actions {
        [
            (Event::Key(Key::Home), Self::SelectTop),
            (Event::Key(Key::Up), Self::SelectUp),
            (Event::Key(Key::PageUp), Self::SelectUpPage),
            (Event::Key(Key::End), Self::SelectBottom),
            (Event::Key(Key::Down), Self::SelectDown),
            (Event::Key(Key::PageDown), Self::SelectDownPage),
            (Event::Key(Key::Right), Self::Expand),
            (Event::Char('+'), Self::ExpandRecursive),
            (Event::Char('>'), Self::ExpandAll),
            (Event::Key(Key::Left), Self::Collapse),
            (Event::Char('-'), Self::CollapseRecursive),
            (Event::Char('<'), Self::CollapseAll),
            (Event::Key(Key::Enter), Self::ToggleState),
        ]
        .into()
    }

    /// Remove from action map.
    ///
    /// Return true if removed.
    pub fn remove(&self, actions: &mut Actions) -> bool {
        let events = self.events(actions);
        for event in &events {
            actions.remove(event);
        }
        !events.is_empty()
    }

    /// Events for the action.
    pub fn events(&self, actions: &Actions) -> Vec<Event> {
        actions
            .into_iter()
            .filter_map(|(event, action)| if action == self { Some(event.clone()) } else { None })
            .collect()
    }
}