Skip to content

Commit

Permalink
Bug fix: Reconfigure tree properly after closing view.
Browse files Browse the repository at this point in the history
This patch merges the last child of a container node to the parent. This
avoids the bug where uneven spaced Views would be created. To reproduce:
1. `vsplit`
2. `split`
3. `quit`
4. `vsplit`

With this patch the bug cannot be seen anymore.
  • Loading branch information
useche committed Mar 25, 2024
1 parent 47995bf commit e503163
Showing 1 changed file with 40 additions and 20 deletions.
60 changes: 40 additions & 20 deletions helix-view/src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,33 +214,53 @@ impl Tree {
node
}

pub fn remove(&mut self, index: ViewId) {
let mut stack = Vec::new();
fn get_container(&mut self, index: ViewId) -> &mut Container {
match &mut self.nodes[index] {
Node {
content: Content::Container(container),
..
} => container,
_ => unreachable!(),
}
}

fn remove_or_replace(&mut self, child: ViewId, replacement: Option<ViewId>) {
let parent = self.nodes[child].parent;

self.nodes.remove(child);

let container = self.get_container(parent);
let pos = container
.children
.iter()
.position(|&item| item == child)
.unwrap();

if let Some(new) = replacement {
container.children[pos] = new;
self.nodes[new].parent = parent;
} else {
container.children.remove(pos);
}
}

pub fn remove(&mut self, index: ViewId) {
if self.focus == index {
// focus on something else
self.focus = self.prev();
}

stack.push(index);
let parent = self.nodes[index].parent;
let parent_is_root = parent == self.root;

while let Some(index) = stack.pop() {
let parent_id = self.nodes[index].parent;
if let Node {
content: Content::Container(container),
..
} = &mut self.nodes[parent_id]
{
if let Some(pos) = container.children.iter().position(|&child| child == index) {
container.children.remove(pos);
// TODO: if container now only has one child, remove it and place child in parent
if container.children.is_empty() && parent_id != self.root {
// if container now empty, remove it
stack.push(parent_id);
}
}
}
self.nodes.remove(index);
self.remove_or_replace(index, None);

let parent_container = self.get_container(parent);
if parent_container.children.len() == 1 && !parent_is_root {
// Lets merge the only child back to its grandparent so that Views
// are equally spaced.
let sibling = parent_container.children.pop().unwrap();
self.remove_or_replace(parent, Some(sibling));
}

self.recalculate()
Expand Down

0 comments on commit e503163

Please sign in to comment.