@@ -0,0 +1,173 @@
2+use slotmap::{DefaultKey as Key, HopSlotMap};
5+// the dimensions are recomputed on windo resize/tree change.
9+ // (container, index inside the container)
10+ current: (Key, usize),
15+ nodes: HopSlotMap<Key, Node>,
17+ // used for traversals
18+ stack: Vec<(Key, Rect)>,
23+ Container(Box<Container>),
27+ pub fn container(area: Rect) -> Self {
28+ Self::Container(Box::new(Container::new()))
31+ pub fn view(view: View) -> Self {
32+ Self::View(Box::new(view))
36+// TODO: screen coord to container + container coordinate helpers
41+ // could explore stacked/tabbed
44+pub struct Container {
51+ pub fn new() -> Self {
53+ layout: Layout::Horizontal,
54+ children: Vec::new(),
55+ area: Rect::default(),
61+ pub fn new(area: Rect) -> Self {
62+ let root = Node::container(area);
63+ let mut nodes = HopSlotMap::new();
64+ let root = nodes.insert(root);
69+ focus: Key::default(),
77+ pub fn insert(&mut self, view: View) -> Key {
78+ let node = self.nodes.insert(Node::view(view));
79+ let (id, pos) = self.current;
80+ let container = match &mut self.nodes[id] {
81+ Node::Container(container) => container,
85+ // insert node after the current item if there is children already
86+ let pos = if container.children.is_empty() {
92+ container.children.insert(pos, node);
93+ // focus the new node
94+ self.current = (id, pos);
97+ // recalculate all the sizes
103+ pub fn views(&mut self) -> impl Iterator<Item = (&mut View, bool)> {
104+ let focus = self.focus;
107+ .filter_map(move |(key, node)| match node {
108+ Node::View(view) => Some((view.as_mut(), focus == key)),
109+ Node::Container(..) => None,
113+ pub fn get(&self, index: Key) -> &View {
114+ match &self.nodes[index] {
115+ Node::View(view) => view,
116+ _ => unreachable!(),
120+ pub fn get_mut(&mut self, index: Key) -> &mut View {
121+ match &mut self.nodes[index] {
122+ Node::View(view) => view,
123+ _ => unreachable!(),
127+ pub fn resize(&mut self, area: Rect) {
132+ pub fn traverse(&mut self) {
133+ self.stack.push((self.root, self.area));
137+ // a) node is view, give it whole area
138+ // b) node is container, calculate areas for each child and push them on the stack
140+ while let Some((key, area)) = self.stack.pop() {
141+ let node = &mut self.nodes[key];
144+ Node::View(view) => {
145+ // debug!!("setting view area {:?}", area);
148+ Node::Container(container) => {
149+ // debug!!("setting container area {:?}", area);
150+ container.area = area;
152+ match container.layout {
153+ Layout::Vertical => unimplemented!(),
154+ Layout::Horizontal => {
155+ let len = container.children.len() as u16;
157+ let width = area.width / len;
159+ let mut child_x = area.x;
161+ for (_i, child) in container.children.iter().enumerate() {
162+ let area = Rect::new(child_x, area.y, width, area.height);
165+ self.stack.push((*child, area));