Calculate previous and next sibling in tree

This commit is contained in:
Joscha 2022-06-17 20:49:17 +02:00
parent 54fc4b59ce
commit 9a351b5eb3
2 changed files with 30 additions and 26 deletions

View file

@ -103,19 +103,10 @@ impl<M: Msg> TreeView<M> {
tree: &mut Tree<M>, tree: &mut Tree<M>,
id: &mut M::Id, id: &mut M::Id,
) -> bool { ) -> bool {
if let Some(siblings) = tree.siblings(id) { if let Some(prev_sibling) = tree.prev_sibling(id) {
let prev_sibling = siblings *id = prev_sibling;
.iter() true
.zip(siblings.iter().skip(1)) } else if tree.parent(id).is_none() {
.find(|(_, s)| *s == id)
.map(|(s, _)| s);
if let Some(prev_sibling) = prev_sibling {
*id = prev_sibling.clone();
true
} else {
false
}
} else {
// We're at the root of our tree, so we need to move to the root of // We're at the root of our tree, so we need to move to the root of
// the previous tree. // the previous tree.
if let Some(prev_tree_id) = store.prev_tree(tree.root()).await { if let Some(prev_tree_id) = store.prev_tree(tree.root()).await {
@ -125,6 +116,8 @@ impl<M: Msg> TreeView<M> {
} else { } else {
false false
} }
} else {
false
} }
} }
@ -137,19 +130,10 @@ impl<M: Msg> TreeView<M> {
tree: &mut Tree<M>, tree: &mut Tree<M>,
id: &mut M::Id, id: &mut M::Id,
) -> bool { ) -> bool {
if let Some(siblings) = tree.siblings(id) { if let Some(next_sibling) = tree.next_sibling(id) {
let next_sibling = siblings *id = next_sibling;
.iter() true
.zip(siblings.iter().skip(1)) } else if tree.parent(id).is_none() {
.find(|(s, _)| *s == id)
.map(|(_, s)| s);
if let Some(next_sibling) = next_sibling {
*id = next_sibling.clone();
true
} else {
false
}
} else {
// We're at the root of our tree, so we need to move to the root of // We're at the root of our tree, so we need to move to the root of
// the next tree. // the next tree.
if let Some(next_tree_id) = store.next_tree(tree.root()).await { if let Some(next_tree_id) = store.next_tree(tree.root()).await {
@ -159,6 +143,8 @@ impl<M: Msg> TreeView<M> {
} else { } else {
false false
} }
} else {
false
} }
} }

View file

@ -99,6 +99,24 @@ impl<M: Msg> Tree<M> {
None None
} }
} }
pub fn prev_sibling(&self, id: &M::Id) -> Option<M::Id> {
let siblings = self.siblings(id)?;
siblings
.iter()
.zip(siblings.iter().skip(1))
.find(|(_, s)| *s == id)
.map(|(s, _)| s.clone())
}
pub fn next_sibling(&self, id: &M::Id) -> Option<M::Id> {
let siblings = self.siblings(id)?;
siblings
.iter()
.zip(siblings.iter().skip(1))
.find(|(s, _)| *s == id)
.map(|(_, s)| s.clone())
}
} }
#[async_trait] #[async_trait]