Browse Source

Merge pull request #1014 from AppFlowy-IO/refactor/document_tree

Refactor/document tree
Nathan.fooo 2 năm trước cách đây
mục cha
commit
b24c4413e8

+ 24 - 3
shared-lib/lib-ot/src/core/document/attributes.rs

@@ -1,7 +1,10 @@
+use serde::{Deserialize, Serialize};
 use std::collections::HashMap;
 
-#[derive(Clone, serde::Serialize, serde::Deserialize)]
-pub struct NodeAttributes(pub HashMap<String, Option<String>>);
+pub type AttributeMap = HashMap<String, Option<String>>;
+
+#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
+pub struct NodeAttributes(pub AttributeMap);
 
 impl Default for NodeAttributes {
     fn default() -> Self {
@@ -9,13 +12,31 @@ impl Default for NodeAttributes {
     }
 }
 
+impl std::ops::Deref for NodeAttributes {
+    type Target = AttributeMap;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+impl std::ops::DerefMut for NodeAttributes {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.0
+    }
+}
+
 impl NodeAttributes {
     pub fn new() -> NodeAttributes {
         NodeAttributes(HashMap::new())
     }
 
+    pub fn to_inner(&self) -> AttributeMap {
+        self.0.clone()
+    }
+
     pub fn compose(a: &NodeAttributes, b: &NodeAttributes) -> NodeAttributes {
-        let mut new_map: HashMap<String, Option<String>> = b.0.clone();
+        let mut new_map: AttributeMap = b.0.clone();
 
         for (key, value) in &a.0 {
             if b.0.contains_key(key.as_str()) {

+ 98 - 40
shared-lib/lib-ot/src/core/document/document.rs

@@ -1,13 +1,13 @@
-use crate::core::document::position::Position;
+use crate::core::document::position::Path;
 use crate::core::{
     DocumentOperation, NodeAttributes, NodeData, NodeSubTree, OperationTransform, TextDelta, Transaction,
 };
 use crate::errors::{ErrorBuilder, OTError, OTErrorCode};
-use indextree::{Arena, NodeId};
+use indextree::{Arena, Children, FollowingSiblings, NodeId};
 
 pub struct DocumentTree {
-    pub arena: Arena<NodeData>,
-    pub root: NodeId,
+    arena: Arena<NodeData>,
+    root: NodeId,
 }
 
 impl Default for DocumentTree {
@@ -19,32 +19,42 @@ impl Default for DocumentTree {
 impl DocumentTree {
     pub fn new() -> DocumentTree {
         let mut arena = Arena::new();
+
         let root = arena.new_node(NodeData::new("root"));
         DocumentTree { arena, root }
     }
 
-    pub fn node_at_path(&self, position: &Position) -> Option<NodeId> {
-        if position.is_empty() {
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use lib_ot::core::{DocumentOperation, DocumentTree, NodeSubTree, Path};
+    /// let nodes = vec![NodeSubTree::new("text")];
+    /// let root_path: Path = vec![0].into();
+    /// let op = DocumentOperation::Insert {path: root_path.clone(),nodes };
+    ///
+    /// let mut document = DocumentTree::new();
+    /// document.apply_op(&op).unwrap();
+    /// let node_id = document.node_at_path(&root_path).unwrap();
+    /// let node_path = document.path_of_node(node_id);
+    /// debug_assert_eq!(node_path, root_path);
+    /// ```
+    pub fn node_at_path<T: Into<Path>>(&self, path: T) -> Option<NodeId> {
+        let path = path.into();
+        if path.is_empty() {
             return Some(self.root);
         }
 
         let mut iterate_node = self.root;
-
-        for id in &position.0 {
-            let child = self.child_at_index_of_path(iterate_node, *id);
-            iterate_node = match child {
-                Some(node) => node,
-                None => return None,
-            };
+        for id in path.iter() {
+            iterate_node = self.child_from_node_with_index(iterate_node, *id)?;
         }
-
         Some(iterate_node)
     }
 
-    pub fn path_of_node(&self, node_id: NodeId) -> Position {
+    pub fn path_of_node(&self, node_id: NodeId) -> Path {
         let mut path: Vec<usize> = Vec::new();
-
-        let mut ancestors = node_id.ancestors(&self.arena);
+        let mut ancestors = node_id.ancestors(&self.arena).skip(1);
         let mut current_node = node_id;
         let mut parent = ancestors.next();
 
@@ -56,15 +66,13 @@ impl DocumentTree {
             parent = ancestors.next();
         }
 
-        Position(path)
+        Path(path)
     }
 
     fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
         let mut counter: usize = 0;
-
         let mut children_iterator = parent_node.children(&self.arena);
         let mut node = children_iterator.next();
-
         while node.is_some() {
             if node.unwrap() == child_node {
                 return counter;
@@ -77,9 +85,30 @@ impl DocumentTree {
         counter
     }
 
-    fn child_at_index_of_path(&self, at_node: NodeId, index: usize) -> Option<NodeId> {
+    ///
+    /// # Arguments
+    ///
+    /// * `at_node`:
+    /// * `index`:
+    ///
+    /// returns: Option<NodeId>
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use lib_ot::core::{DocumentOperation, DocumentTree, NodeSubTree, Path};
+    /// let node = NodeSubTree::new("text");
+    /// let inserted_path: Path = vec![0].into();
+    ///
+    /// let mut document = DocumentTree::new();
+    /// document.apply_op(&DocumentOperation::Insert {path: inserted_path.clone(),nodes: vec![node.clone()] }).unwrap();
+    ///
+    /// let inserted_note = document.node_at_path(&inserted_path).unwrap();
+    /// let inserted_data = document.get_node_data(inserted_note).unwrap();
+    /// assert_eq!(inserted_data.node_type, node.note_type);
+    /// ```
+    pub fn child_from_node_with_index(&self, at_node: NodeId, index: usize) -> Option<NodeId> {
         let children = at_node.children(&self.arena);
-
         for (counter, child) in children.enumerate() {
             if counter == index {
                 return Some(child);
@@ -89,6 +118,32 @@ impl DocumentTree {
         None
     }
 
+    pub fn children_from_node(&self, node_id: NodeId) -> Children<'_, NodeData> {
+        node_id.children(&self.arena)
+    }
+
+    pub fn get_node_data(&self, node_id: NodeId) -> Option<&NodeData> {
+        Some(self.arena.get(node_id)?.get())
+    }
+
+    ///
+    /// # Arguments
+    ///
+    /// * `node_id`: if the node_is is None, then will use root node_id.
+    ///
+    /// returns number of the children of the root node
+    ///
+    pub fn number_of_children(&self, node_id: Option<NodeId>) -> usize {
+        match node_id {
+            None => self.root.children(&self.arena).count(),
+            Some(node_id) => node_id.children(&self.arena).count(),
+        }
+    }
+
+    pub fn following_siblings(&self, node_id: NodeId) -> FollowingSiblings<'_, NodeData> {
+        node_id.following_siblings(&self.arena)
+    }
+
     pub fn apply(&mut self, transaction: Transaction) -> Result<(), OTError> {
         for op in &transaction.operations {
             self.apply_op(op)?;
@@ -96,7 +151,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_op(&mut self, op: &DocumentOperation) -> Result<(), OTError> {
+    pub fn apply_op(&mut self, op: &DocumentOperation) -> Result<(), OTError> {
         match op {
             DocumentOperation::Insert { path, nodes } => self.apply_insert(path, nodes),
             DocumentOperation::Update { path, attributes, .. } => self.apply_update(path, attributes),
@@ -105,36 +160,39 @@ impl DocumentTree {
         }
     }
 
-    fn apply_insert(&mut self, path: &Position, nodes: &[Box<NodeSubTree>]) -> Result<(), OTError> {
-        let parent_path = &path.0[0..(path.0.len() - 1)];
-        let last_index = path.0[path.0.len() - 1];
+    fn apply_insert(&mut self, path: &Path, nodes: &[NodeSubTree]) -> Result<(), OTError> {
+        debug_assert!(!path.is_empty());
+        if path.is_empty() {
+            return Err(OTErrorCode::PathIsEmpty.into());
+        }
+
+        let (parent_path, last_path) = path.split_at(path.0.len() - 1);
+        let last_index = *last_path.first().unwrap();
         let parent_node = self
-            .node_at_path(&Position(parent_path.to_vec()))
+            .node_at_path(parent_path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
 
-        self.insert_child_at_index(parent_node, last_index, nodes.as_ref())
+        self.insert_child_at_index(parent_node, last_index, nodes)
     }
 
     fn insert_child_at_index(
         &mut self,
         parent: NodeId,
         index: usize,
-        insert_children: &[Box<NodeSubTree>],
+        insert_children: &[NodeSubTree],
     ) -> Result<(), OTError> {
         if index == 0 && parent.children(&self.arena).next().is_none() {
             self.append_subtree(&parent, insert_children);
             return Ok(());
         }
 
-        let children_length = parent.children(&self.arena).fold(0, |counter, _| counter + 1);
-
-        if index == children_length {
+        if index == parent.children(&self.arena).count() {
             self.append_subtree(&parent, insert_children);
             return Ok(());
         }
 
         let node_to_insert = self
-            .child_at_index_of_path(parent, index)
+            .child_from_node_with_index(parent, index)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
 
         self.insert_subtree_before(&node_to_insert, insert_children);
@@ -142,25 +200,25 @@ impl DocumentTree {
     }
 
     // recursive append the subtrees to the node
-    fn append_subtree(&mut self, parent: &NodeId, insert_children: &[Box<NodeSubTree>]) {
+    fn append_subtree(&mut self, parent: &NodeId, insert_children: &[NodeSubTree]) {
         for child in insert_children {
             let child_id = self.arena.new_node(child.to_node_data());
             parent.append(child_id, &mut self.arena);
 
-            self.append_subtree(&child_id, child.children.as_ref());
+            self.append_subtree(&child_id, &child.children);
         }
     }
 
-    fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[Box<NodeSubTree>]) {
+    fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[NodeSubTree]) {
         for child in insert_children {
             let child_id = self.arena.new_node(child.to_node_data());
             before.insert_before(child_id, &mut self.arena);
 
-            self.append_subtree(&child_id, child.children.as_ref());
+            self.append_subtree(&child_id, &child.children);
         }
     }
 
-    fn apply_update(&mut self, path: &Position, attributes: &NodeAttributes) -> Result<(), OTError> {
+    fn apply_update(&mut self, path: &Path, attributes: &NodeAttributes) -> Result<(), OTError> {
         let update_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
@@ -177,7 +235,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_delete(&mut self, path: &Position, len: usize) -> Result<(), OTError> {
+    fn apply_delete(&mut self, path: &Path, len: usize) -> Result<(), OTError> {
         let mut update_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
@@ -193,7 +251,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_text_edit(&mut self, path: &Position, delta: &TextDelta) -> Result<(), OTError> {
+    fn apply_text_edit(&mut self, path: &Path, delta: &TextDelta) -> Result<(), OTError> {
         let edit_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;

+ 26 - 32
shared-lib/lib-ot/src/core/document/document_operation.rs

@@ -1,36 +1,30 @@
-use crate::core::document::position::Position;
+use crate::core::document::position::Path;
 use crate::core::{NodeAttributes, NodeSubTree, TextDelta};
 
 #[derive(Clone, serde::Serialize, serde::Deserialize)]
 #[serde(tag = "op")]
 pub enum DocumentOperation {
     #[serde(rename = "insert")]
-    Insert {
-        path: Position,
-        nodes: Vec<Box<NodeSubTree>>,
-    },
+    Insert { path: Path, nodes: Vec<NodeSubTree> },
     #[serde(rename = "update")]
     Update {
-        path: Position,
+        path: Path,
         attributes: NodeAttributes,
         #[serde(rename = "oldAttributes")]
         old_attributes: NodeAttributes,
     },
     #[serde(rename = "delete")]
-    Delete {
-        path: Position,
-        nodes: Vec<Box<NodeSubTree>>,
-    },
+    Delete { path: Path, nodes: Vec<NodeSubTree> },
     #[serde(rename = "text-edit")]
     TextEdit {
-        path: Position,
+        path: Path,
         delta: TextDelta,
         inverted: TextDelta,
     },
 }
 
 impl DocumentOperation {
-    pub fn path(&self) -> &Position {
+    pub fn path(&self) -> &Path {
         match self {
             DocumentOperation::Insert { path, .. } => path,
             DocumentOperation::Update { path, .. } => path,
@@ -64,7 +58,7 @@ impl DocumentOperation {
             },
         }
     }
-    pub fn clone_with_new_path(&self, path: Position) -> DocumentOperation {
+    pub fn clone_with_new_path(&self, path: Path) -> DocumentOperation {
         match self {
             DocumentOperation::Insert { nodes, .. } => DocumentOperation::Insert {
                 path,
@@ -93,11 +87,11 @@ impl DocumentOperation {
     pub fn transform(a: &DocumentOperation, b: &DocumentOperation) -> DocumentOperation {
         match a {
             DocumentOperation::Insert { path: a_path, nodes } => {
-                let new_path = Position::transform(a_path, b.path(), nodes.len() as i64);
+                let new_path = Path::transform(a_path, b.path(), nodes.len() as i64);
                 b.clone_with_new_path(new_path)
             }
             DocumentOperation::Delete { path: a_path, nodes } => {
-                let new_path = Position::transform(a_path, b.path(), nodes.len() as i64);
+                let new_path = Path::transform(a_path, b.path(), nodes.len() as i64);
                 b.clone_with_new_path(new_path)
             }
             _ => b.clone(),
@@ -107,12 +101,12 @@ impl DocumentOperation {
 
 #[cfg(test)]
 mod tests {
-    use crate::core::{Delta, DocumentOperation, NodeAttributes, NodeSubTree, Position};
+    use crate::core::{Delta, DocumentOperation, NodeAttributes, NodeSubTree, Path};
 
     #[test]
     fn test_transform_path_1() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 1]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 1]), 1) }.0,
             vec![0, 2]
         );
     }
@@ -120,7 +114,7 @@ mod tests {
     #[test]
     fn test_transform_path_2() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 2]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 2]), 1) }.0,
             vec![0, 3]
         );
     }
@@ -128,7 +122,7 @@ mod tests {
     #[test]
     fn test_transform_path_3() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 2, 7, 8, 9]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 2, 7, 8, 9]), 1) }.0,
             vec![0, 3, 7, 8, 9]
         );
     }
@@ -136,15 +130,15 @@ mod tests {
     #[test]
     fn test_transform_path_not_changed() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1, 2]), &Position(vec![0, 0, 7, 8, 9]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1, 2]), &Path(vec![0, 0, 7, 8, 9]), 1) }.0,
             vec![0, 0, 7, 8, 9]
         );
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1, 2]), &Position(vec![0, 1]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1, 2]), &Path(vec![0, 1]), 1) }.0,
             vec![0, 1]
         );
         assert_eq!(
-            { Position::transform(&Position(vec![1, 1]), &Position(vec![1, 0]), 1) }.0,
+            { Path::transform(&Path(vec![1, 1]), &Path(vec![1, 0]), 1) }.0,
             vec![1, 0]
         );
     }
@@ -152,7 +146,7 @@ mod tests {
     #[test]
     fn test_transform_delta() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 1]), 5) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 1]), 5) }.0,
             vec![0, 6]
         );
     }
@@ -160,8 +154,8 @@ mod tests {
     #[test]
     fn test_serialize_insert_operation() {
         let insert = DocumentOperation::Insert {
-            path: Position(vec![0, 1]),
-            nodes: vec![Box::new(NodeSubTree::new("text"))],
+            path: Path(vec![0, 1]),
+            nodes: vec![NodeSubTree::new("text")],
         };
         let result = serde_json::to_string(&insert).unwrap();
         assert_eq!(
@@ -173,13 +167,13 @@ mod tests {
     #[test]
     fn test_serialize_insert_sub_trees() {
         let insert = DocumentOperation::Insert {
-            path: Position(vec![0, 1]),
-            nodes: vec![Box::new(NodeSubTree {
-                node_type: "text".into(),
+            path: Path(vec![0, 1]),
+            nodes: vec![NodeSubTree {
+                note_type: "text".into(),
                 attributes: NodeAttributes::new(),
                 delta: None,
-                children: vec![Box::new(NodeSubTree::new("text"))],
-            })],
+                children: vec![NodeSubTree::new("text")],
+            }],
         };
         let result = serde_json::to_string(&insert).unwrap();
         assert_eq!(
@@ -191,7 +185,7 @@ mod tests {
     #[test]
     fn test_serialize_update_operation() {
         let insert = DocumentOperation::Update {
-            path: Position(vec![0, 1]),
+            path: Path(vec![0, 1]),
             attributes: NodeAttributes::new(),
             old_attributes: NodeAttributes::new(),
         };
@@ -205,7 +199,7 @@ mod tests {
     #[test]
     fn test_serialize_text_edit_operation() {
         let insert = DocumentOperation::TextEdit {
-            path: Position(vec![0, 1]),
+            path: Path(vec![0, 1]),
             delta: Delta::new(),
             inverted: Delta::new(),
         };

+ 10 - 6
shared-lib/lib-ot/src/core/document/node.rs

@@ -1,6 +1,7 @@
 use crate::core::{NodeAttributes, TextDelta};
+use serde::{Deserialize, Serialize};
 
-#[derive(Clone)]
+#[derive(Clone, Eq, PartialEq, Debug)]
 pub struct NodeData {
     pub node_type: String,
     pub attributes: NodeAttributes,
@@ -17,21 +18,24 @@ impl NodeData {
     }
 }
 
-#[derive(Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Serialize, Deserialize, Eq, PartialEq)]
 pub struct NodeSubTree {
     #[serde(rename = "type")]
-    pub node_type: String,
+    pub note_type: String,
+
     pub attributes: NodeAttributes,
+
     #[serde(skip_serializing_if = "Option::is_none")]
     pub delta: Option<TextDelta>,
+
     #[serde(skip_serializing_if = "Vec::is_empty")]
-    pub children: Vec<Box<NodeSubTree>>,
+    pub children: Vec<NodeSubTree>,
 }
 
 impl NodeSubTree {
     pub fn new(node_type: &str) -> NodeSubTree {
         NodeSubTree {
-            node_type: node_type.into(),
+            note_type: node_type.into(),
             attributes: NodeAttributes::new(),
             delta: None,
             children: Vec::new(),
@@ -40,7 +44,7 @@ impl NodeSubTree {
 
     pub fn to_node_data(&self) -> NodeData {
         NodeData {
-            node_type: self.node_type.clone(),
+            node_type: self.note_type.clone(),
             attributes: self.attributes.clone(),
             delta: self.delta.clone(),
         }

+ 47 - 16
shared-lib/lib-ot/src/core/document/position.rs

@@ -1,18 +1,55 @@
-#[derive(Clone, serde::Serialize, serde::Deserialize)]
-pub struct Position(pub Vec<usize>);
+use serde::{Deserialize, Serialize};
 
-impl Position {
-    pub fn is_empty(&self) -> bool {
-        self.0.is_empty()
+#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
+pub struct Path(pub Vec<usize>);
+
+impl std::ops::Deref for Path {
+    type Target = Vec<usize>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+impl std::convert::Into<Path> for usize {
+    fn into(self) -> Path {
+        Path(vec![self])
+    }
+}
+
+impl std::convert::Into<Path> for &usize {
+    fn into(self) -> Path {
+        Path(vec![*self])
+    }
+}
+
+impl std::convert::Into<Path> for &Path {
+    fn into(self) -> Path {
+        self.clone()
+    }
+}
+
+impl From<Vec<usize>> for Path {
+    fn from(v: Vec<usize>) -> Self {
+        Path(v)
+    }
+}
+
+impl From<&Vec<usize>> for Path {
+    fn from(values: &Vec<usize>) -> Self {
+        Path(values.clone())
     }
-    pub fn len(&self) -> usize {
-        self.0.len()
+}
+
+impl From<&[usize]> for Path {
+    fn from(values: &[usize]) -> Self {
+        Path(values.to_vec())
     }
 }
 
-impl Position {
+impl Path {
     // delta is default to be 1
-    pub fn transform(pre_insert_path: &Position, b: &Position, offset: i64) -> Position {
+    pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path {
         if pre_insert_path.len() > b.len() {
             return b.clone();
         }
@@ -36,12 +73,6 @@ impl Position {
         }
         prefix.append(&mut suffix);
 
-        Position(prefix)
-    }
-}
-
-impl From<Vec<usize>> for Position {
-    fn from(v: Vec<usize>) -> Self {
-        Position(v)
+        Path(prefix)
     }
 }

+ 73 - 25
shared-lib/lib-ot/src/core/document/transaction.rs

@@ -1,7 +1,6 @@
-use crate::core::document::position::Position;
-use crate::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree};
+use crate::core::document::position::Path;
+use crate::core::{AttributeMap, DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree};
 use indextree::NodeId;
-use std::collections::HashMap;
 
 pub struct Transaction {
     pub operations: Vec<DocumentOperation>,
@@ -26,17 +25,65 @@ impl<'a> TransactionBuilder<'a> {
         }
     }
 
-    pub fn insert_nodes_at_path(&mut self, path: &Position, nodes: &[Box<NodeSubTree>]) {
+    ///
+    ///
+    /// # Arguments
+    ///
+    /// * `path`: the path that is used to save the nodes
+    /// * `nodes`: the nodes you will be save in the path
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// // -- 0 (root)
+    /// //      0 -- text_1
+    /// //      1 -- text_2
+    /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder};
+    /// let mut document = DocumentTree::new();
+    /// let transaction = TransactionBuilder::new(&document)
+    ///     .insert_nodes_at_path(0,vec![ NodeSubTree::new("text_1"),  NodeSubTree::new("text_2")])
+    ///     .finalize();
+    ///  document.apply(transaction).unwrap();
+    ///
+    ///  document.node_at_path(vec![0, 0]);
+    /// ```
+    ///
+    pub fn insert_nodes_at_path<T: Into<Path>>(self, path: T, nodes: Vec<NodeSubTree>) -> Self {
         self.push(DocumentOperation::Insert {
-            path: path.clone(),
-            nodes: nodes.to_vec(),
-        });
+            path: path.into(),
+            nodes,
+        })
+    }
+
+    ///
+    ///
+    /// # Arguments
+    ///
+    /// * `path`: the path that is used to save the nodes
+    /// * `node`: the node data will be saved in the path
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// // 0
+    /// // -- 0
+    /// //    |-- text
+    /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder};
+    /// let mut document = DocumentTree::new();
+    /// let transaction = TransactionBuilder::new(&document)
+    ///     .insert_node_at_path(0, NodeSubTree::new("text"))
+    ///     .finalize();
+    ///  document.apply(transaction).unwrap();
+    /// ```
+    ///
+    pub fn insert_node_at_path<T: Into<Path>>(self, path: T, node: NodeSubTree) -> Self {
+        self.insert_nodes_at_path(path, vec![node])
     }
 
-    pub fn update_attributes_at_path(&mut self, path: &Position, attributes: HashMap<String, Option<String>>) {
-        let mut old_attributes: HashMap<String, Option<String>> = HashMap::new();
+    pub fn update_attributes_at_path(self, path: &Path, attributes: AttributeMap) -> Self {
+        let mut old_attributes: AttributeMap = AttributeMap::new();
         let node = self.document.node_at_path(path).unwrap();
-        let node_data = self.document.arena.get(node).unwrap().get();
+        let node_data = self.document.get_node_data(node).unwrap();
 
         for key in attributes.keys() {
             let old_attrs = &node_data.attributes;
@@ -54,43 +101,44 @@ impl<'a> TransactionBuilder<'a> {
         })
     }
 
-    pub fn delete_node_at_path(&mut self, path: &Position) {
-        self.delete_nodes_at_path(path, 1);
+    pub fn delete_node_at_path(self, path: &Path) -> Self {
+        self.delete_nodes_at_path(path, 1)
     }
 
-    pub fn delete_nodes_at_path(&mut self, path: &Position, length: usize) {
+    pub fn delete_nodes_at_path(mut self, path: &Path, length: usize) -> Self {
         let mut node = self.document.node_at_path(path).unwrap();
-        let mut deleted_nodes: Vec<Box<NodeSubTree>> = Vec::new();
-
+        let mut deleted_nodes = vec![];
         for _ in 0..length {
             deleted_nodes.push(self.get_deleted_nodes(node));
-            node = node.following_siblings(&self.document.arena).next().unwrap();
+            node = self.document.following_siblings(node).next().unwrap();
         }
 
         self.operations.push(DocumentOperation::Delete {
             path: path.clone(),
             nodes: deleted_nodes,
-        })
+        });
+        self
     }
 
-    fn get_deleted_nodes(&self, node_id: NodeId) -> Box<NodeSubTree> {
-        let node_data = self.document.arena.get(node_id).unwrap().get();
+    fn get_deleted_nodes(&self, node_id: NodeId) -> NodeSubTree {
+        let node_data = self.document.get_node_data(node_id).unwrap();
 
-        let mut children: Vec<Box<NodeSubTree>> = vec![];
-        node_id.children(&self.document.arena).for_each(|child_id| {
+        let mut children = vec![];
+        self.document.children_from_node(node_id).for_each(|child_id| {
             children.push(self.get_deleted_nodes(child_id));
         });
 
-        Box::new(NodeSubTree {
-            node_type: node_data.node_type.clone(),
+        NodeSubTree {
+            note_type: node_data.node_type.clone(),
             attributes: node_data.attributes.clone(),
             delta: node_data.delta.clone(),
             children,
-        })
+        }
     }
 
-    pub fn push(&mut self, op: DocumentOperation) {
+    pub fn push(mut self, op: DocumentOperation) -> Self {
         self.operations.push(op);
+        self
     }
 
     pub fn finalize(self) -> Transaction {

+ 1 - 0
shared-lib/lib-ot/src/errors.rs

@@ -75,6 +75,7 @@ pub enum OTErrorCode {
     RevisionIDConflict,
     Internal,
     PathNotFound,
+    PathIsEmpty,
 }
 
 pub struct ErrorBuilder {

+ 1 - 147
shared-lib/lib-ot/tests/main.rs

@@ -1,147 +1 @@
-use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Position, TransactionBuilder};
-use lib_ot::errors::OTErrorCode;
-use std::collections::HashMap;
-
-#[test]
-fn main() {
-    // Create a new arena
-    let _document = DocumentTree::new();
-}
-
-#[test]
-fn test_documents() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    assert!(document.node_at_path(&vec![0].into()).is_some());
-    let node = document.node_at_path(&vec![0].into()).unwrap();
-    let node_data = document.arena.get(node).unwrap().get();
-    assert_eq!(node_data.node_type, "text");
-
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.update_attributes_at_path(
-            &vec![0].into(),
-            HashMap::from([("subtype".into(), Some("bullet-list".into()))]),
-        );
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.delete_node_at_path(&vec![0].into());
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-    assert!(document.node_at_path(&vec![0].into()).is_none());
-}
-
-#[test]
-fn test_inserts_nodes() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-}
-
-#[test]
-fn test_inserts_subtrees() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(
-            &vec![0].into(),
-            &[Box::new(NodeSubTree {
-                node_type: "text".into(),
-                attributes: NodeAttributes::new(),
-                delta: None,
-                children: vec![Box::new(NodeSubTree::new("image"))],
-            })],
-        );
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let node = document.node_at_path(&Position(vec![0, 0])).unwrap();
-    let data = document.arena.get(node).unwrap().get();
-    assert_eq!(data.node_type, "image");
-}
-
-#[test]
-fn test_update_nodes() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.update_attributes_at_path(&vec![1].into(), HashMap::from([("bolded".into(), Some("true".into()))]));
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let node = document.node_at_path(&Position(vec![1])).unwrap();
-    let node_data = document.arena.get(node).unwrap().get();
-    let is_bold = node_data.attributes.0.get("bolded").unwrap().clone();
-    assert_eq!(is_bold.unwrap(), "true");
-}
-
-#[test]
-fn test_delete_nodes() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.delete_node_at_path(&Position(vec![1]));
-        tb.finalize()
-    };
-    document.apply(transaction).unwrap();
-
-    let len = document.root.children(&document.arena).fold(0, |count, _| count + 1);
-    assert_eq!(len, 2);
-}
-
-#[test]
-fn test_errors() {
-    let mut document = DocumentTree::new();
-    let transaction = {
-        let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![100].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.finalize()
-    };
-    let result = document.apply(transaction);
-    assert_eq!(result.err().unwrap().code, OTErrorCode::PathNotFound);
-}
+mod node;

+ 2 - 0
shared-lib/lib-ot/tests/node/mod.rs

@@ -0,0 +1,2 @@
+mod script;
+mod test;

+ 76 - 0
shared-lib/lib-ot/tests/node/script.rs

@@ -0,0 +1,76 @@
+use lib_ot::core::{DocumentTree, NodeAttributes, NodeData, NodeSubTree, Path, TransactionBuilder};
+
+pub enum NodeScript {
+    InsertNode { path: Path, node: NodeSubTree },
+    InsertAttributes { path: Path, attributes: NodeAttributes },
+    DeleteNode { path: Path },
+    AssertNumberOfChildrenAtPath { path: Option<Path>, len: usize },
+    AssertNode { path: Path, expected: Option<NodeSubTree> },
+}
+
+pub struct NodeTest {
+    node_tree: DocumentTree,
+}
+
+impl NodeTest {
+    pub fn new() -> Self {
+        Self {
+            node_tree: DocumentTree::new(),
+        }
+    }
+
+    pub fn run_scripts(&mut self, scripts: Vec<NodeScript>) {
+        for script in scripts {
+            self.run_script(script);
+        }
+    }
+
+    pub fn run_script(&mut self, script: NodeScript) {
+        match script {
+            NodeScript::InsertNode { path, node } => {
+                let transaction = TransactionBuilder::new(&self.node_tree)
+                    .insert_node_at_path(path, node)
+                    .finalize();
+
+                self.node_tree.apply(transaction).unwrap();
+            }
+            NodeScript::InsertAttributes { path, attributes } => {
+                let transaction = TransactionBuilder::new(&self.node_tree)
+                    .update_attributes_at_path(&path, attributes.to_inner())
+                    .finalize();
+                self.node_tree.apply(transaction).unwrap();
+            }
+            NodeScript::DeleteNode { path } => {
+                let transaction = TransactionBuilder::new(&self.node_tree)
+                    .delete_node_at_path(&path)
+                    .finalize();
+                self.node_tree.apply(transaction).unwrap();
+            }
+            NodeScript::AssertNode { path, expected } => {
+                let node_id = self.node_tree.node_at_path(path);
+
+                match node_id {
+                    None => assert!(node_id.is_none()),
+                    Some(node_id) => {
+                        let node_data = self.node_tree.get_node_data(node_id).cloned();
+                        assert_eq!(node_data, expected.and_then(|e| Some(e.to_node_data())));
+                    }
+                }
+            }
+            NodeScript::AssertNumberOfChildrenAtPath {
+                path,
+                len: expected_len,
+            } => match path {
+                None => {
+                    let len = self.node_tree.number_of_children(None);
+                    assert_eq!(len, expected_len)
+                }
+                Some(path) => {
+                    let node_id = self.node_tree.node_at_path(path).unwrap();
+                    let len = self.node_tree.number_of_children(Some(node_id));
+                    assert_eq!(len, expected_len)
+                }
+            },
+        }
+    }
+}

+ 184 - 0
shared-lib/lib-ot/tests/node/test.rs

@@ -0,0 +1,184 @@
+use crate::node::script::NodeScript::*;
+use crate::node::script::NodeTest;
+use lib_ot::core::{NodeAttributes, NodeSubTree, Path};
+
+#[test]
+fn node_insert_test() {
+    let mut test = NodeTest::new();
+    let inserted_node = NodeSubTree::new("text");
+    let path: Path = 0.into();
+    let scripts = vec![
+        InsertNode {
+            path: path.clone(),
+            node: inserted_node.clone(),
+        },
+        AssertNode {
+            path,
+            expected: Some(inserted_node),
+        },
+    ];
+    test.run_scripts(scripts);
+}
+
+#[test]
+fn node_insert_node_with_children_test() {
+    let mut test = NodeTest::new();
+    let inserted_node = NodeSubTree {
+        note_type: "text".into(),
+        attributes: NodeAttributes::new(),
+        delta: None,
+        children: vec![NodeSubTree::new("image")],
+    };
+    let path: Path = 0.into();
+    let scripts = vec![
+        InsertNode {
+            path: path.clone(),
+            node: inserted_node.clone(),
+        },
+        AssertNode {
+            path,
+            expected: Some(inserted_node),
+        },
+    ];
+    test.run_scripts(scripts);
+}
+
+#[test]
+fn node_insert_multi_nodes_test() {
+    let mut test = NodeTest::new();
+    let path_1: Path = 0.into();
+    let node_1 = NodeSubTree::new("text_1");
+
+    let path_2: Path = 1.into();
+    let node_2 = NodeSubTree::new("text_2");
+
+    let path_3: Path = 2.into();
+    let node_3 = NodeSubTree::new("text_3");
+
+    let scripts = vec![
+        InsertNode {
+            path: path_1.clone(),
+            node: node_1.clone(),
+        },
+        InsertNode {
+            path: path_2.clone(),
+            node: node_2.clone(),
+        },
+        InsertNode {
+            path: path_3.clone(),
+            node: node_3.clone(),
+        },
+        AssertNode {
+            path: path_1,
+            expected: Some(node_1),
+        },
+        AssertNode {
+            path: path_2,
+            expected: Some(node_2),
+        },
+        AssertNode {
+            path: path_3,
+            expected: Some(node_3),
+        },
+    ];
+    test.run_scripts(scripts);
+}
+
+#[test]
+fn node_insert_node_in_ordered_nodes_test() {
+    let mut test = NodeTest::new();
+    let path_1: Path = 0.into();
+    let node_1 = NodeSubTree::new("text_1");
+
+    let path_2: Path = 1.into();
+    let node_2_1 = NodeSubTree::new("text_2_1");
+    let node_2_2 = NodeSubTree::new("text_2_2");
+
+    let path_3: Path = 2.into();
+    let node_3 = NodeSubTree::new("text_3");
+
+    let path_4: Path = 3.into();
+
+    let scripts = vec![
+        InsertNode {
+            path: path_1.clone(),
+            node: node_1.clone(),
+        },
+        InsertNode {
+            path: path_2.clone(),
+            node: node_2_1.clone(),
+        },
+        InsertNode {
+            path: path_3.clone(),
+            node: node_3.clone(),
+        },
+        // 0:note_1 , 1: note_2_1, 2: note_3
+        InsertNode {
+            path: path_2.clone(),
+            node: node_2_2.clone(),
+        },
+        // 0:note_1 , 1:note_2_2,  2: note_2_1, 3: note_3
+        AssertNode {
+            path: path_1,
+            expected: Some(node_1),
+        },
+        AssertNode {
+            path: path_2,
+            expected: Some(node_2_2),
+        },
+        AssertNode {
+            path: path_3,
+            expected: Some(node_2_1),
+        },
+        AssertNode {
+            path: path_4,
+            expected: Some(node_3),
+        },
+        AssertNumberOfChildrenAtPath { path: None, len: 4 },
+    ];
+    test.run_scripts(scripts);
+}
+
+#[test]
+fn node_insert_with_attributes_test() {
+    let mut test = NodeTest::new();
+    let path: Path = 0.into();
+    let mut inserted_node = NodeSubTree::new("text");
+    inserted_node.attributes.insert("bold".to_string(), Some("true".into()));
+    inserted_node
+        .attributes
+        .insert("underline".to_string(), Some("true".into()));
+
+    let scripts = vec![
+        InsertNode {
+            path: path.clone(),
+            node: inserted_node.clone(),
+        },
+        InsertAttributes {
+            path: path.clone(),
+            attributes: inserted_node.attributes.clone(),
+        },
+        AssertNode {
+            path,
+            expected: Some(inserted_node),
+        },
+    ];
+    test.run_scripts(scripts);
+}
+
+#[test]
+fn node_delete_test() {
+    let mut test = NodeTest::new();
+    let inserted_node = NodeSubTree::new("text");
+
+    let path: Path = 0.into();
+    let scripts = vec![
+        InsertNode {
+            path: path.clone(),
+            node: inserted_node.clone(),
+        },
+        DeleteNode { path: path.clone() },
+        AssertNode { path, expected: None },
+    ];
+    test.run_scripts(scripts);
+}