From c4260fc17fa9f5bc6f1ec39efb7e3a66d2cea12e Mon Sep 17 00:00:00 2001 From: ynqa Date: Sat, 10 Feb 2024 12:02:39 +0900 Subject: [PATCH] tree: use cursor --- src/core/tree.rs | 48 +++++++++++++++++++++++------------------ src/core/tree/render.rs | 8 +++---- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/src/core/tree.rs b/src/core/tree.rs index 1e779c8d..f53ba687 100644 --- a/src/core/tree.rs +++ b/src/core/tree.rs @@ -1,52 +1,58 @@ mod node; + pub use node::{Node, NodeWithDepth}; mod render; pub use render::Renderer; mod build; pub use build::Builder; -#[derive(Clone, Default)] +use crate::core::cursor::Cursor; + +#[derive(Clone)] pub struct Tree { root: Node, - cache: Vec, - position: usize, + cursor: Cursor>, } impl Tree { pub fn new(root: Node) -> Self { Self { root: root.clone(), - cache: root.flatten(), - position: 0, + cursor: Cursor::new(root.flatten()), } } - pub fn nodes_with_depth(&self) -> Vec { - self.cache.clone() + pub fn nodes(&self) -> Vec { + self.cursor.contents().clone() + } + + pub fn position(&self) -> usize { + self.cursor.position() } pub fn get(&self) -> String { - self.cache.get(self.position).unwrap().data.clone() + self.cursor + .contents() + .get(self.position()) + .unwrap() + .data + .clone() + } + + pub fn toggle(&mut self) { + self.root.toggle(self.cursor.position()); + self.cursor = Cursor::new_with_position(self.root.flatten(), self.position()); } pub fn backward(&mut self) -> bool { - if 0 < self.position { - self.position -= 1; - return true; - } - false + self.cursor.backward() } pub fn forward(&mut self) -> bool { - if !self.cache.is_empty() && self.position < self.cache.len() - 1 { - self.position += 1; - return true; - } - false + self.cursor.forward() } - pub fn toggle(&mut self) { - self.root.toggle(self.position); - self.cache = self.root.flatten(); + pub fn move_to_head(&mut self) { + self.cursor.move_to_head() } } diff --git a/src/core/tree/render.rs b/src/core/tree/render.rs index 83112b86..ed657632 100644 --- a/src/core/tree/render.rs +++ b/src/core/tree/render.rs @@ -25,11 +25,11 @@ impl Renderable for Renderer { fn make_pane(&self, width: u16) -> crate::pane::Pane { let matrix = self .tree - .nodes_with_depth() + .nodes() .iter() .enumerate() .map(|(i, item)| { - if i == self.tree.position { + if i == self.tree.position() { Graphemes::new_with_style( format!("{}{}{}", self.cursor, " ".repeat(item.depth), item.data), self.cursor_style, @@ -49,7 +49,7 @@ impl Renderable for Renderer { .collect::>(); let trimed = matrix.iter().map(|row| trim(width as usize, row)).collect(); - Pane::new(trimed, self.tree.position, self.lines) + Pane::new(trimed, self.tree.position(), self.lines) } fn handle_event(&mut self, event: &Event) { @@ -87,7 +87,7 @@ impl Renderable for Renderer { } fn postrun(&mut self) { - self.tree.position = 0; + self.tree.move_to_head() } }