Skip to content

Commit

Permalink
tree: use cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
ynqa committed Feb 10, 2024
1 parent 36f0940 commit c4260fc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 25 deletions.
48 changes: 27 additions & 21 deletions src/core/tree.rs
Original file line number Diff line number Diff line change
@@ -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<NodeWithDepth>,
position: usize,
cursor: Cursor<Vec<NodeWithDepth>>,
}

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<NodeWithDepth> {
self.cache.clone()
pub fn nodes(&self) -> Vec<NodeWithDepth> {
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()
}
}
8 changes: 4 additions & 4 deletions src/core/tree/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -49,7 +49,7 @@ impl Renderable for Renderer {
.collect::<Vec<Graphemes>>();

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) {
Expand Down Expand Up @@ -87,7 +87,7 @@ impl Renderable for Renderer {
}

fn postrun(&mut self) {
self.tree.position = 0;
self.tree.move_to_head()
}
}

Expand Down

0 comments on commit c4260fc

Please sign in to comment.