tui-rs icon indicating copy to clipboard operation
tui-rs copied to clipboard

Add support for multiple selections in List<'a>

Open philippeitis opened this issue 3 years ago • 1 comments

I'm building a TUI application, where I'd like the option to allow selecting multiple items in my list - for instance, deleting them, or editing many items at once. However, the List struct does not support this as is, and this requires copy-pasting list.rs and modifying just a few lines of code, since List requires access to private members to function correctly.

If possible, I'd like to be able to select multiple items at once with minimal overhead, and with reuse of existing tui structs. I think that modifying ListState to support a few selection styles, and track selection direction would be a good solution - i.e:

enum Direction {
    Up,
    Down,
}

enum Selection {
    None,
    Single(usize),
    Multiple(BTreeSet<usize>, Direction)
}

impl Selection {
    /// Gets the visible selection.
    pub fn focused_selection(&self) -> Option<usize>;
    /// Returns true if item is selected.
    pub fn is_selected(&self, usize) -> bool;
}

pub struct ListState {
    offset: usize,
    selected: Selection,
}

impl ListState {
    /// Adds the selection
    pub fn add_selection(&mut self, index: usize);
    /// Select many items
    pub fn add_selections(&mut self, indices: Iter<Item=usize>);
    /// Selects only this item
    pub fn select(&mut self, index: Option<usize>);
    /// Deselects everything
    pub fn deselect_all(&mut self);
    /// Deselects single item
    pub fn deselect(&mut self, index: usize);
}

This allows maintaining existing functions as is (eg. select one item at a time), and allows extended functionality via new functions, which I think is an ideal solution. There shouldn't be too much additional code required to support the various types of selections, and the overhead is pretty minuscule. I already have a multiple selection variant working, so I can clean it up and send a PR if this is something that you'd be willing to merge.

philippeitis avatar Apr 02 '21 21:04 philippeitis

Hey 👋 . Support for multiple selections could indeed be a very nice addition to the List and potentially to the Table widgets. I have to say that I'm bit confused about what you mean by selection direction in this context though. Other than that your design makes a lot of sense and I would welcome a PR on this feature.

fdehau avatar May 02 '21 21:05 fdehau