feat!: cache last tree structure to simplify events

Things like key up/down dont require the items anymore to be used.
Instead a cached last state from last render is used.
This commit is contained in:
EdJoPaTo
2024-05-01 01:45:54 +02:00
parent 701be9315d
commit fdd2c5436a
5 changed files with 88 additions and 88 deletions
+4 -4
View File
@@ -142,11 +142,11 @@ fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> std::io::Res
KeyCode::Char('\n' | ' ') => app.state.toggle_selected(), KeyCode::Char('\n' | ' ') => app.state.toggle_selected(),
KeyCode::Left => app.state.key_left(), KeyCode::Left => app.state.key_left(),
KeyCode::Right => app.state.key_right(), KeyCode::Right => app.state.key_right(),
KeyCode::Down => app.state.key_down(&app.items), KeyCode::Down => app.state.key_down(),
KeyCode::Up => app.state.key_up(&app.items), KeyCode::Up => app.state.key_up(),
KeyCode::Esc => app.state.select(Vec::new()), KeyCode::Esc => app.state.select(Vec::new()),
KeyCode::Home => app.state.select_first(&app.items), KeyCode::Home => app.state.select_first(),
KeyCode::End => app.state.select_last(&app.items), KeyCode::End => app.state.select_last(),
KeyCode::PageDown => app.state.scroll_down(3), KeyCode::PageDown => app.state.scroll_down(3),
KeyCode::PageUp => app.state.scroll_up(3), KeyCode::PageUp => app.state.scroll_up(3),
_ => false, _ => false,
+4 -30
View File
@@ -56,35 +56,9 @@ where
result result
} }
#[cfg(test)]
fn get_example_tree_items() -> Vec<TreeItem<'static, &'static str>> {
vec![
TreeItem::new_leaf("a", "Alfa"),
TreeItem::new(
"b",
"Bravo",
vec![
TreeItem::new_leaf("c", "Charlie"),
TreeItem::new(
"d",
"Delta",
vec![
TreeItem::new_leaf("e", "Echo"),
TreeItem::new_leaf("f", "Foxtrot"),
],
)
.expect("all item identifiers are unique"),
TreeItem::new_leaf("g", "Golf"),
],
)
.expect("all item identifiers are unique"),
TreeItem::new_leaf("h", "Hotel"),
]
}
#[test] #[test]
fn get_opened_nothing_opened_is_top_level() { fn get_opened_nothing_opened_is_top_level() {
let items = get_example_tree_items(); let items = TreeItem::example();
let opened = HashSet::new(); let opened = HashSet::new();
let result = flatten(&opened, &items); let result = flatten(&opened, &items);
let result_text = result let result_text = result
@@ -96,7 +70,7 @@ fn get_opened_nothing_opened_is_top_level() {
#[test] #[test]
fn get_opened_wrong_opened_is_only_top_level() { fn get_opened_wrong_opened_is_only_top_level() {
let items = get_example_tree_items(); let items = TreeItem::example();
let mut opened = HashSet::new(); let mut opened = HashSet::new();
opened.insert(vec!["a"]); opened.insert(vec!["a"]);
opened.insert(vec!["b", "d"]); opened.insert(vec!["b", "d"]);
@@ -110,7 +84,7 @@ fn get_opened_wrong_opened_is_only_top_level() {
#[test] #[test]
fn get_opened_one_is_opened() { fn get_opened_one_is_opened() {
let items = get_example_tree_items(); let items = TreeItem::example();
let mut opened = HashSet::new(); let mut opened = HashSet::new();
opened.insert(vec!["b"]); opened.insert(vec!["b"]);
let result = flatten(&opened, &items); let result = flatten(&opened, &items);
@@ -123,7 +97,7 @@ fn get_opened_one_is_opened() {
#[test] #[test]
fn get_opened_all_opened() { fn get_opened_all_opened() {
let items = get_example_tree_items(); let items = TreeItem::example();
let mut opened = HashSet::new(); let mut opened = HashSet::new();
opened.insert(vec!["b"]); opened.insert(vec!["b"]);
opened.insert(vec!["b", "d"]); opened.insert(vec!["b", "d"]);
+8 -6
View File
@@ -191,6 +191,7 @@ where
} }
let visible = state.flatten(&self.items); let visible = state.flatten(&self.items);
state.last_biggest_index = visible.len().saturating_sub(1);
if visible.is_empty() { if visible.is_empty() {
return; return;
} }
@@ -206,7 +207,7 @@ where
}; };
// Ensure last line is still visible // Ensure last line is still visible
let mut start = state.offset.min(visible.len().saturating_sub(1)); let mut start = state.offset.min(state.last_biggest_index);
if let Some(ensure_index_in_view) = ensure_index_in_view { if let Some(ensure_index_in_view) = ensure_index_in_view {
start = start.min(ensure_index_in_view); start = start.min(ensure_index_in_view);
@@ -260,11 +261,8 @@ where
let mut current_height = 0; let mut current_height = 0;
let has_selection = !state.selected.is_empty(); let has_selection = !state.selected.is_empty();
#[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_possible_truncation)]
for flattened in visible.into_iter().skip(state.offset).take(end - start) { for flattened in visible.iter().skip(state.offset).take(end - start) {
let Flattened { let Flattened { identifier, item } = flattened;
ref identifier,
item,
} = flattened;
let x = area.x; let x = area.x;
let y = area.y + current_height; let y = area.y + current_height;
@@ -324,6 +322,10 @@ where
buf.set_style(area, self.highlight_style); buf.set_style(area, self.highlight_style);
} }
} }
state.last_visible_identifiers = visible
.into_iter()
.map(|flattened| flattened.identifier)
.collect();
} }
} }
+28
View File
@@ -141,6 +141,34 @@ where
} }
} }
impl TreeItem<'static, &'static str> {
#[cfg(test)]
pub(crate) fn example() -> Vec<Self> {
vec![
TreeItem::new_leaf("a", "Alfa"),
TreeItem::new(
"b",
"Bravo",
vec![
TreeItem::new_leaf("c", "Charlie"),
TreeItem::new(
"d",
"Delta",
vec![
TreeItem::new_leaf("e", "Echo"),
TreeItem::new_leaf("f", "Foxtrot"),
],
)
.expect("all item identifiers are unique"),
TreeItem::new_leaf("g", "Golf"),
],
)
.expect("all item identifiers are unique"),
TreeItem::new_leaf("h", "Hotel"),
]
}
}
#[test] #[test]
#[should_panic = "duplicate identifiers"] #[should_panic = "duplicate identifiers"]
fn tree_item_new_errors_with_duplicate_identifiers() { fn tree_item_new_errors_with_duplicate_identifiers() {
+44 -48
View File
@@ -16,12 +16,14 @@ use crate::tree_item::TreeItem;
/// ///
/// let mut state = TreeState::<Identifier>::default(); /// let mut state = TreeState::<Identifier>::default();
/// ``` /// ```
#[derive(Debug, Default, Clone)] #[derive(Debug, Default)]
pub struct TreeState<Identifier> { pub struct TreeState<Identifier> {
pub(super) offset: usize, pub(super) offset: usize,
pub(super) opened: HashSet<Vec<Identifier>>, pub(super) opened: HashSet<Vec<Identifier>>,
pub(super) selected: Vec<Identifier>, pub(super) selected: Vec<Identifier>,
pub(super) ensure_selected_in_view_on_next_render: bool, pub(super) ensure_selected_in_view_on_next_render: bool,
pub(super) last_biggest_index: usize,
pub(super) last_visible_identifiers: Vec<Vec<Identifier>>,
} }
impl<Identifier> TreeState<Identifier> impl<Identifier> TreeState<Identifier>
@@ -38,6 +40,11 @@ where
self.opened.iter().cloned().collect() self.opened.iter().cloned().collect()
} }
#[must_use]
pub fn selected(&self) -> Vec<Identifier> {
self.selected.clone()
}
/// Get a flat list of all visible (= below open) [`TreeItem`]s with this `TreeState`. /// Get a flat list of all visible (= below open) [`TreeItem`]s with this `TreeState`.
#[must_use] #[must_use]
pub fn flatten<'a>( pub fn flatten<'a>(
@@ -47,11 +54,6 @@ where
flatten(&self.opened, items) flatten(&self.opened, items)
} }
#[must_use]
pub fn selected(&self) -> Vec<Identifier> {
self.selected.clone()
}
/// Selects the given identifier. /// Selects the given identifier.
/// ///
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
@@ -128,22 +130,24 @@ where
/// Select the first node. /// Select the first node.
/// ///
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
pub fn select_first(&mut self, items: &[TreeItem<Identifier>]) -> bool { pub fn select_first(&mut self) -> bool {
let identifier = items let identifier = self
.last_visible_identifiers
.first() .first()
.map_or(Vec::new(), |item| vec![item.identifier.clone()]); .cloned()
.unwrap_or_default();
self.select(identifier) self.select(identifier)
} }
/// Select the last visible node. /// Select the last visible node.
/// ///
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
pub fn select_last(&mut self, items: &[TreeItem<Identifier>]) -> bool { pub fn select_last(&mut self) -> bool {
let visible = self.flatten(items); let new_identifier = self
let new_identifier = visible .last_visible_identifiers
.into_iter()
.last() .last()
.map_or(Vec::new(), |flattened| flattened.identifier); .cloned()
.unwrap_or_default();
self.select(new_identifier) self.select(new_identifier)
} }
@@ -152,17 +156,13 @@ where
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
/// ///
/// This can be useful for mouse clicks. /// This can be useful for mouse clicks.
pub fn select_visible_index( pub fn select_visible_index(&mut self, new_index: usize) -> bool {
&mut self, let new_index = new_index.min(self.last_biggest_index);
items: &[TreeItem<Identifier>], let new_identifier = self
new_index: usize, .last_visible_identifiers
) -> bool { .get(new_index)
let visible = self.flatten(items); .cloned()
let new_index = new_index.min(visible.len().saturating_sub(1)); .unwrap_or_default();
let new_identifier = visible
.into_iter()
.nth(new_index)
.map_or(Vec::new(), |flattened| flattened.identifier);
self.select(new_identifier) self.select(new_identifier)
} }
@@ -174,35 +174,27 @@ where
/// ///
/// ``` /// ```
/// # use tui_tree_widget::TreeState; /// # use tui_tree_widget::TreeState;
/// # let items = vec![];
/// # type Identifier = usize; /// # type Identifier = usize;
/// # let mut state = TreeState::<Identifier>::default(); /// # let mut state = TreeState::<Identifier>::default();
/// // Move the selection one down /// // Move the selection one down
/// state.select_visible_relative(&items, |current| { /// state.select_visible_relative(|current| {
/// current.map_or(0, |current| current.saturating_add(1)) /// current.map_or(0, |current| current.saturating_add(1))
/// }); /// });
/// ``` /// ```
/// ///
/// For more examples take a look into the source code of [`key_up`](Self::key_up) or [`key_down`](Self::key_down). /// For more examples take a look into the source code of [`key_up`](Self::key_up) or [`key_down`](Self::key_down).
/// They are implemented with this method. /// They are implemented with this method.
pub fn select_visible_relative<F>( pub fn select_visible_relative<F>(&mut self, change_function: F) -> bool
&mut self,
items: &[TreeItem<Identifier>],
change_function: F,
) -> bool
where where
F: FnOnce(Option<usize>) -> usize, F: FnOnce(Option<usize>) -> usize,
{ {
let visible = self.flatten(items); let visible = &self.last_visible_identifiers;
let current_identifier = self.selected(); let current_identifier = &self.selected;
let current_index = visible let current_index = visible
.iter() .iter()
.position(|flattened| flattened.identifier == current_identifier); .position(|identifier| identifier == current_identifier);
let new_index = change_function(current_index).min(visible.len().saturating_sub(1)); let new_index = change_function(current_index).min(self.last_biggest_index);
let new_identifier = visible let new_identifier = visible.get(new_index).cloned().unwrap_or_default();
.into_iter()
.nth(new_index)
.map_or(Vec::new(), |flattened| flattened.identifier);
self.select(new_identifier) self.select(new_identifier)
} }
@@ -223,19 +215,23 @@ where
/// Scroll the specified amount of lines down /// Scroll the specified amount of lines down
/// ///
/// In contrast to [`scroll_up()`](Self::scroll_up) this can not return whether the view position changed or not as the actual change is determined on render. /// Returns `true` when the scroll position changed.
/// Always returns `true`. /// Returns `false` when the scrolling has reached the last [`TreeItem`].
pub fn scroll_down(&mut self, lines: usize) -> bool { pub fn scroll_down(&mut self, lines: usize) -> bool {
self.offset = self.offset.saturating_add(lines); let before = self.offset;
true self.offset = self
.offset
.saturating_add(lines)
.min(self.last_biggest_index);
before != self.offset
} }
/// Handles the up arrow key. /// Handles the up arrow key.
/// Moves up in the current depth or to its parent. /// Moves up in the current depth or to its parent.
/// ///
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
pub fn key_up(&mut self, items: &[TreeItem<Identifier>]) -> bool { pub fn key_up(&mut self) -> bool {
self.select_visible_relative(items, |current| { self.select_visible_relative(|current| {
current.map_or(usize::MAX, |current| current.saturating_sub(1)) current.map_or(usize::MAX, |current| current.saturating_sub(1))
}) })
} }
@@ -244,8 +240,8 @@ where
/// Moves down in the current depth or into a child node. /// Moves down in the current depth or into a child node.
/// ///
/// Returns `true` when the selection changed. /// Returns `true` when the selection changed.
pub fn key_down(&mut self, items: &[TreeItem<Identifier>]) -> bool { pub fn key_down(&mut self) -> bool {
self.select_visible_relative(items, |current| { self.select_visible_relative(|current| {
current.map_or(0, |current| current.saturating_add(1)) current.map_or(0, |current| current.saturating_add(1))
}) })
} }