From 800e02d85e1621e0737685e778a44305f4790a62 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 16:49:09 +0800 Subject: [PATCH 01/10] refactor: remove Box in DocumentOperation --- .../lib-ot/src/core/document/document.rs | 66 +++++++++++-------- .../src/core/document/document_operation.rs | 56 +++++++--------- shared-lib/lib-ot/src/core/document/node.rs | 2 +- .../lib-ot/src/core/document/position.rs | 23 ++++--- .../lib-ot/src/core/document/transaction.rs | 21 +++--- shared-lib/lib-ot/tests/main.rs | 40 +++++------ 6 files changed, 107 insertions(+), 101 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 204a920ad8..76fb7ed3fa 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -1,4 +1,4 @@ -use crate::core::document::position::Position; +use crate::core::document::position::Path; use crate::core::{ DocumentOperation, NodeAttributes, NodeData, NodeSubTree, OperationTransform, TextDelta, Transaction, }; @@ -23,27 +23,41 @@ impl DocumentTree { DocumentTree { arena, root } } - pub fn node_at_path(&self, position: &Position) -> Option { - if position.is_empty() { + pub fn node_at_path(&self, path: &Path) -> Option { + 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_at_index_of_path(iterate_node, *id)?; } - Some(iterate_node) } - pub fn path_of_node(&self, node_id: NodeId) -> Position { + /// + /// + /// # Arguments + /// + /// * `node_id`: + /// + /// returns: Path + /// + /// # Examples + /// + /// ``` + /// use lib_ot::core::{DocumentOperation, DocumentTree, NodeSubTree, Path}; + /// let text_node = NodeSubTree::new("text"); + /// let path: Path = vec![0].into(); + /// let op = DocumentOperation::Insert {path: path.clone(),nodes: vec![text_node + /// ]}; + /// let mut document = DocumentTree::new(); + /// document.apply_op(&op).unwrap(); + /// let node_id = document.node_at_path(&path).unwrap(); + /// + /// ``` + pub fn path_of_node(&self, node_id: NodeId) -> Path { let mut path: Vec = Vec::new(); - let mut ancestors = node_id.ancestors(&self.arena); let mut current_node = node_id; let mut parent = ancestors.next(); @@ -56,7 +70,7 @@ impl DocumentTree { parent = ancestors.next(); } - Position(path) + Path(path) } fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize { @@ -96,7 +110,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,21 +119,21 @@ impl DocumentTree { } } - fn apply_insert(&mut self, path: &Position, nodes: &[Box]) -> Result<(), OTError> { + fn apply_insert(&mut self, path: &Path, nodes: &[NodeSubTree]) -> Result<(), OTError> { let parent_path = &path.0[0..(path.0.len() - 1)]; let last_index = path.0[path.0.len() - 1]; let parent_node = self - .node_at_path(&Position(parent_path.to_vec())) + .node_at_path(&Path(parent_path.to_vec())) .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], + insert_children: &[NodeSubTree], ) -> Result<(), OTError> { if index == 0 && parent.children(&self.arena).next().is_none() { self.append_subtree(&parent, insert_children); @@ -142,25 +156,25 @@ impl DocumentTree { } // recursive append the subtrees to the node - fn append_subtree(&mut self, parent: &NodeId, insert_children: &[Box]) { + 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]) { + 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 +191,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 +207,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())?; diff --git a/shared-lib/lib-ot/src/core/document/document_operation.rs b/shared-lib/lib-ot/src/core/document/document_operation.rs index 29bfdcc04f..a1143a1883 100644 --- a/shared-lib/lib-ot/src/core/document/document_operation.rs +++ b/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>, - }, + Insert { path: Path, nodes: Vec }, #[serde(rename = "update")] Update { - path: Position, + path: Path, attributes: NodeAttributes, #[serde(rename = "oldAttributes")] old_attributes: NodeAttributes, }, #[serde(rename = "delete")] - Delete { - path: Position, - nodes: Vec>, - }, + Delete { path: Path, nodes: Vec }, #[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 { + path: Path(vec![0, 1]), + nodes: vec![NodeSubTree { node_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(), }; diff --git a/shared-lib/lib-ot/src/core/document/node.rs b/shared-lib/lib-ot/src/core/document/node.rs index e74c7d4918..3aef136c9c 100644 --- a/shared-lib/lib-ot/src/core/document/node.rs +++ b/shared-lib/lib-ot/src/core/document/node.rs @@ -25,7 +25,7 @@ pub struct NodeSubTree { #[serde(skip_serializing_if = "Option::is_none")] pub delta: Option, #[serde(skip_serializing_if = "Vec::is_empty")] - pub children: Vec>, + pub children: Vec, } impl NodeSubTree { diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 541ff98fb2..5be8fb4401 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -1,18 +1,17 @@ #[derive(Clone, serde::Serialize, serde::Deserialize)] -pub struct Position(pub Vec); +pub struct Path(pub Vec); -impl Position { - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - pub fn len(&self) -> usize { - self.0.len() +impl std::ops::Deref for Path { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 } } -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 +35,12 @@ impl Position { } prefix.append(&mut suffix); - Position(prefix) + Path(prefix) } } -impl From> for Position { +impl From> for Path { fn from(v: Vec) -> Self { - Position(v) + Path(v) } } diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index c5b00523da..f08f828706 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -1,4 +1,4 @@ -use crate::core::document::position::Position; +use crate::core::document::position::Path; use crate::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree}; use indextree::NodeId; use std::collections::HashMap; @@ -26,14 +26,14 @@ impl<'a> TransactionBuilder<'a> { } } - pub fn insert_nodes_at_path(&mut self, path: &Position, nodes: &[Box]) { + pub fn insert_nodes_at_path(&mut self, path: &Path, nodes: &[NodeSubTree]) { self.push(DocumentOperation::Insert { path: path.clone(), nodes: nodes.to_vec(), }); } - pub fn update_attributes_at_path(&mut self, path: &Position, attributes: HashMap>) { + pub fn update_attributes_at_path(&mut self, path: &Path, attributes: HashMap>) { let mut old_attributes: HashMap> = HashMap::new(); let node = self.document.node_at_path(path).unwrap(); let node_data = self.document.arena.get(node).unwrap().get(); @@ -54,14 +54,13 @@ impl<'a> TransactionBuilder<'a> { }) } - pub fn delete_node_at_path(&mut self, path: &Position) { + pub fn delete_node_at_path(&mut self, path: &Path) { 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) { let mut node = self.document.node_at_path(path).unwrap(); - let mut deleted_nodes: Vec> = 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(); @@ -73,20 +72,20 @@ impl<'a> TransactionBuilder<'a> { }) } - fn get_deleted_nodes(&self, node_id: NodeId) -> Box { + fn get_deleted_nodes(&self, node_id: NodeId) -> NodeSubTree { let node_data = self.document.arena.get(node_id).unwrap().get(); - let mut children: Vec> = vec![]; + let mut children = vec![]; node_id.children(&self.document.arena).for_each(|child_id| { children.push(self.get_deleted_nodes(child_id)); }); - Box::new(NodeSubTree { + NodeSubTree { node_type: node_data.node_type.clone(), attributes: node_data.attributes.clone(), delta: node_data.delta.clone(), children, - }) + } } pub fn push(&mut self, op: DocumentOperation) { diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index ae7080656e..49a986ab6e 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -1,4 +1,4 @@ -use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Position, TransactionBuilder}; +use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder}; use lib_ot::errors::OTErrorCode; use std::collections::HashMap; @@ -13,7 +13,7 @@ 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.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); tb.finalize() }; document.apply(transaction).unwrap(); @@ -47,16 +47,16 @@ 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.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![2].into(), &[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.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); tb.finalize() }; document.apply(transaction).unwrap(); @@ -69,18 +69,18 @@ fn test_inserts_subtrees() { let mut tb = TransactionBuilder::new(&document); tb.insert_nodes_at_path( &vec![0].into(), - &[Box::new(NodeSubTree { + &[NodeSubTree { node_type: "text".into(), attributes: NodeAttributes::new(), delta: None, - children: vec![Box::new(NodeSubTree::new("image"))], - })], + children: vec![NodeSubTree::new("image")], + }], ); tb.finalize() }; document.apply(transaction).unwrap(); - let node = document.node_at_path(&Position(vec![0, 0])).unwrap(); + let node = document.node_at_path(&Path(vec![0, 0])).unwrap(); let data = document.arena.get(node).unwrap().get(); assert_eq!(data.node_type, "image"); } @@ -90,9 +90,9 @@ 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.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]); tb.finalize() }; document.apply(transaction).unwrap(); @@ -104,7 +104,7 @@ fn test_update_nodes() { }; document.apply(transaction).unwrap(); - let node = document.node_at_path(&Position(vec![1])).unwrap(); + let node = document.node_at_path(&Path(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"); @@ -115,16 +115,16 @@ 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.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![2].into(), &[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.delete_node_at_path(&Path(vec![1])); tb.finalize() }; document.apply(transaction).unwrap(); @@ -138,8 +138,8 @@ 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.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); + tb.insert_nodes_at_path(&vec![100].into(), &[NodeSubTree::new("text")]); tb.finalize() }; let result = document.apply(transaction); From 294b1bea13a595bc468122f0e633d6ed872973aa Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 16:58:37 +0800 Subject: [PATCH 02/10] refactor: remove Box in DocumentOperation --- shared-lib/lib-ot/src/core/document/position.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 5be8fb4401..54ead9c28a 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -9,6 +9,12 @@ impl std::ops::Deref for Path { } } +impl AsRef for usize { + fn as_ref(&self) -> &Path { + todo!() + } +} + impl Path { // delta is default to be 1 pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path { From 8f5134305e98a41a2bbb21360815c8339a76bdc9 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 17:38:11 +0800 Subject: [PATCH 03/10] refactor: generic insert_nodes method --- .../lib-ot/src/core/document/document.rs | 7 ++- .../lib-ot/src/core/document/position.rs | 37 +++++++++--- .../lib-ot/src/core/document/transaction.rs | 60 ++++++++++++++++++- shared-lib/lib-ot/src/errors.rs | 1 + shared-lib/lib-ot/tests/main.rs | 40 ++++++------- 5 files changed, 112 insertions(+), 33 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 76fb7ed3fa..95508237a4 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -23,7 +23,8 @@ impl DocumentTree { DocumentTree { arena, root } } - pub fn node_at_path(&self, path: &Path) -> Option { + pub fn node_at_path>(&self, path: T) -> Option { + let path = path.into(); if path.is_empty() { return Some(self.root); } @@ -120,8 +121,12 @@ impl DocumentTree { } fn apply_insert(&mut self, path: &Path, nodes: &[NodeSubTree]) -> Result<(), OTError> { + + let parent_path = &path.0[0..(path.0.len() - 1)]; let last_index = path.0[path.0.len() - 1]; + + let parent_node = self .node_at_path(&Path(parent_path.to_vec())) .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?; diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 54ead9c28a..697bde8177 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -9,12 +9,37 @@ impl std::ops::Deref for Path { } } -impl AsRef for usize { - fn as_ref(&self) -> &Path { - todo!() +impl std::convert::Into for usize { + fn into(self) -> Path { + Path(vec![self]) } } +impl std::convert::Into for &usize { + fn into(self) -> Path { + Path(vec![*self]) + } +} + +impl std::convert::Into for &Path { + fn into(self) -> Path { + self.clone() + } +} + +impl From> for Path { + fn from(v: Vec) -> Self { + Path(v) + } +} + +impl From<&Vec> for Path { + fn from(values: &Vec) -> Self { + Path(values.clone()) + } +} + + impl Path { // delta is default to be 1 pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path { @@ -44,9 +69,3 @@ impl Path { Path(prefix) } } - -impl From> for Path { - fn from(v: Vec) -> Self { - Path(v) - } -} diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index f08f828706..bede8ebe2f 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -26,13 +26,67 @@ impl<'a> TransactionBuilder<'a> { } } - pub fn insert_nodes_at_path(&mut self, path: &Path, nodes: &[NodeSubTree]) { + + /// + /// + /// # Arguments + /// + /// * `path`: the path that is used to save the nodes + /// * `nodes`: the nodes you will be save in the path + /// + /// # Examples + /// + /// ``` + /// // 0 + /// // -- 0 + /// // |-- text_1 + /// // |-- text_2 + /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder}; + /// let mut document = DocumentTree::new(); + /// let transaction = { + /// let mut tb = TransactionBuilder::new(&document); + /// tb.insert_nodes_at_path(0,vec![ NodeSubTree::new("text_1"), NodeSubTree::new("text_2")]); + /// tb.finalize() + /// }; + /// document.apply(transaction).unwrap(); + /// + /// document.node_at_path(vec![0, 0]); + /// ``` + /// + pub fn insert_nodes_at_path>(&mut self, path: T, nodes: Vec) { 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 = { + /// let mut tb = TransactionBuilder::new(&document); + /// tb.insert_node_at_path(0, NodeSubTree::new("text")); + /// tb.finalize() + /// }; + /// document.apply(transaction).unwrap(); + /// ``` + /// + pub fn insert_node_at_path>(&mut self, path: T, node: NodeSubTree) { + self.insert_nodes_at_path(path, vec![node]); + } + pub fn update_attributes_at_path(&mut self, path: &Path, attributes: HashMap>) { let mut old_attributes: HashMap> = HashMap::new(); let node = self.document.node_at_path(path).unwrap(); diff --git a/shared-lib/lib-ot/src/errors.rs b/shared-lib/lib-ot/src/errors.rs index eb313c784f..449c662883 100644 --- a/shared-lib/lib-ot/src/errors.rs +++ b/shared-lib/lib-ot/src/errors.rs @@ -75,6 +75,7 @@ pub enum OTErrorCode { RevisionIDConflict, Internal, PathNotFound, + PathIsEmpty, } pub struct ErrorBuilder { diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 49a986ab6e..8ac6aae55a 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -13,13 +13,13 @@ fn test_documents() { let mut document = DocumentTree::new(); let transaction = { let mut tb = TransactionBuilder::new(&document); - tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(0, 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(); + assert!(document.node_at_path(0).is_some()); + let node = document.node_at_path(0).unwrap(); let node_data = document.arena.get(node).unwrap().get(); assert_eq!(node_data.node_type, "text"); @@ -39,7 +39,7 @@ fn test_documents() { tb.finalize() }; document.apply(transaction).unwrap(); - assert!(document.node_at_path(&vec![0].into()).is_none()); + assert!(document.node_at_path(0).is_none()); } #[test] @@ -47,16 +47,16 @@ 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(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(0, NodeSubTree::new("text")); + tb.insert_node_at_path(1, NodeSubTree::new("text")); + tb.insert_node_at_path(2, 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(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(1, NodeSubTree::new("text")); tb.finalize() }; document.apply(transaction).unwrap(); @@ -67,14 +67,14 @@ 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(), - &[NodeSubTree { + tb.insert_node_at_path( + 0, + NodeSubTree { node_type: "text".into(), attributes: NodeAttributes::new(), delta: None, children: vec![NodeSubTree::new("image")], - }], + }, ); tb.finalize() }; @@ -90,9 +90,9 @@ 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(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(&vec![0], NodeSubTree::new("text")); + tb.insert_node_at_path(&vec![1], NodeSubTree::new("text")); + tb.insert_node_at_path(vec![2], NodeSubTree::new("text")); tb.finalize() }; document.apply(transaction).unwrap(); @@ -115,9 +115,9 @@ 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(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(0, NodeSubTree::new("text")); + tb.insert_node_at_path(1, NodeSubTree::new("text")); + tb.insert_node_at_path(2, NodeSubTree::new("text")); tb.finalize() }; document.apply(transaction).unwrap(); @@ -138,8 +138,8 @@ fn test_errors() { let mut document = DocumentTree::new(); let transaction = { let mut tb = TransactionBuilder::new(&document); - tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]); - tb.insert_nodes_at_path(&vec![100].into(), &[NodeSubTree::new("text")]); + tb.insert_node_at_path(0, NodeSubTree::new("text")); + tb.insert_node_at_path(100, NodeSubTree::new("text")); tb.finalize() }; let result = document.apply(transaction); From 89a5ee4a8a9359bd82a154c16057c9f40ffec122 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 17:47:53 +0800 Subject: [PATCH 04/10] fix: potential crash while calling apply_insert if the path is empty --- shared-lib/lib-ot/src/core/document/document.rs | 13 +++++++------ shared-lib/lib-ot/src/core/document/position.rs | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 95508237a4..a20457a656 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -121,14 +121,15 @@ impl DocumentTree { } 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 = &path.0[0..(path.0.len() - 1)]; - let last_index = path.0[path.0.len() - 1]; - - + 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(&Path(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) diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 697bde8177..e45c2556d6 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -39,6 +39,12 @@ impl From<&Vec> for Path { } } +impl From<&[usize]> for Path { + fn from(values: &[usize]) -> Self { + Path(values.to_vec()) + } +} + impl Path { // delta is default to be 1 From d386698e978ff5f4ac99b4dc1df630d13b42a5e9 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 18:05:07 +0800 Subject: [PATCH 05/10] fix: skip root to get the right path --- .../lib-ot/src/core/document/document.rs | 40 ++++++++----------- .../lib-ot/src/core/document/position.rs | 4 +- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index a20457a656..ee7cb7111b 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -23,6 +23,21 @@ impl DocumentTree { DocumentTree { arena, root } } + /// + /// # 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>(&self, path: T) -> Option { let path = path.into(); if path.is_empty() { @@ -36,30 +51,9 @@ impl DocumentTree { Some(iterate_node) } - /// - /// - /// # Arguments - /// - /// * `node_id`: - /// - /// returns: Path - /// - /// # Examples - /// - /// ``` - /// use lib_ot::core::{DocumentOperation, DocumentTree, NodeSubTree, Path}; - /// let text_node = NodeSubTree::new("text"); - /// let path: Path = vec![0].into(); - /// let op = DocumentOperation::Insert {path: path.clone(),nodes: vec![text_node - /// ]}; - /// let mut document = DocumentTree::new(); - /// document.apply_op(&op).unwrap(); - /// let node_id = document.node_at_path(&path).unwrap(); - /// - /// ``` pub fn path_of_node(&self, node_id: NodeId) -> Path { let mut path: Vec = 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(); @@ -76,10 +70,8 @@ impl DocumentTree { 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; diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index e45c2556d6..383581db27 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -1,4 +1,6 @@ -#[derive(Clone, serde::Serialize, serde::Deserialize)] +use serde::{Serialize, Deserialize}; + +#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] pub struct Path(pub Vec); impl std::ops::Deref for Path { From e711bfce1d776618f44f9842a3ed6d213eabe17f Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 19:21:06 +0800 Subject: [PATCH 06/10] chore: udpate test --- shared-lib/lib-ot/src/core/document/document.rs | 2 +- shared-lib/lib-ot/tests/main.rs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index ee7cb7111b..9ced1186d6 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -84,7 +84,7 @@ impl DocumentTree { counter } - fn child_at_index_of_path(&self, at_node: NodeId, index: usize) -> Option { + pub fn child_at_index_of_path(&self, at_node: NodeId, index: usize) -> Option { let children = at_node.children(&self.arena); for (counter, child) in children.enumerate() { diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 8ac6aae55a..45164ecae3 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -1,4 +1,4 @@ -use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder}; +use lib_ot::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder}; use lib_ot::errors::OTErrorCode; use std::collections::HashMap; @@ -85,6 +85,18 @@ fn test_inserts_subtrees() { assert_eq!(data.node_type, "image"); } +#[test] +fn test_insert_node() { + let node = NodeSubTree::new("text"); + let root_path: Path = vec![0].into(); + let op = DocumentOperation::Insert {path: root_path.clone(),nodes: vec![node.clone()] }; + let mut document = DocumentTree::new(); + document.apply_op(&op).unwrap(); + let node_id = document.node_at_path(&root_path).unwrap(); + + assert!(document.child_at_index_of_path(node_id, 0).is_some()); +} + #[test] fn test_update_nodes() { let mut document = DocumentTree::new(); From 9974539946a236550242dbd51b3ebb97d081f87f Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 19:27:15 +0800 Subject: [PATCH 07/10] chore: private the Arena --- .../lib-ot/src/core/document/document.rs | 49 ++++++++++++++++--- .../lib-ot/src/core/document/transaction.rs | 15 +++--- shared-lib/lib-ot/tests/main.rs | 20 ++------ 3 files changed, 54 insertions(+), 30 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 9ced1186d6..a7e97021d2 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -3,10 +3,10 @@ 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, Node, NodeId}; pub struct DocumentTree { - pub arena: Arena, + arena: Arena, pub root: NodeId, } @@ -46,7 +46,7 @@ impl DocumentTree { let mut iterate_node = self.root; for id in path.iter() { - iterate_node = self.child_at_index_of_path(iterate_node, *id)?; + iterate_node = self.child_from_node_with_index(iterate_node, *id)?; } Some(iterate_node) } @@ -84,9 +84,30 @@ impl DocumentTree { counter } - pub fn child_at_index_of_path(&self, at_node: NodeId, index: usize) -> Option { + /// + /// # Arguments + /// + /// * `at_node`: + /// * `index`: + /// + /// returns: Option + /// + /// # 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.node_type); + /// ``` + pub fn child_from_node_with_index(&self, at_node: NodeId, index: usize) -> Option { let children = at_node.children(&self.arena); - for (counter, child) in children.enumerate() { if counter == index { return Some(child); @@ -96,6 +117,22 @@ 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()) + } + + pub fn number_of_children(&self) -> usize { + self.root.children(&self.arena).fold(0, |count, _| count + 1) + } + + 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)?; @@ -146,7 +183,7 @@ impl DocumentTree { } 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); diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index bede8ebe2f..74e7d893bc 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -37,10 +37,9 @@ impl<'a> TransactionBuilder<'a> { /// # Examples /// /// ``` - /// // 0 - /// // -- 0 - /// // |-- text_1 - /// // |-- text_2 + /// // -- 0 (root) + /// // 0 -- text_1 + /// // 1 -- text_2 /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder}; /// let mut document = DocumentTree::new(); /// let transaction = { @@ -90,7 +89,7 @@ impl<'a> TransactionBuilder<'a> { pub fn update_attributes_at_path(&mut self, path: &Path, attributes: HashMap>) { let mut old_attributes: HashMap> = HashMap::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; @@ -117,7 +116,7 @@ impl<'a> TransactionBuilder<'a> { 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 { @@ -127,10 +126,10 @@ impl<'a> TransactionBuilder<'a> { } fn get_deleted_nodes(&self, node_id: NodeId) -> NodeSubTree { - let node_data = self.document.arena.get(node_id).unwrap().get(); + let node_data = self.document.get_node_data(node_id).unwrap(); let mut children = vec![]; - node_id.children(&self.document.arena).for_each(|child_id| { + self.document.children_from_node(node_id).for_each(|child_id| { children.push(self.get_deleted_nodes(child_id)); }); diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 45164ecae3..56c7706c69 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -20,7 +20,7 @@ fn test_documents() { assert!(document.node_at_path(0).is_some()); let node = document.node_at_path(0).unwrap(); - let node_data = document.arena.get(node).unwrap().get(); + let node_data = document.get_node_data(node).unwrap(); assert_eq!(node_data.node_type, "text"); let transaction = { @@ -81,22 +81,10 @@ fn test_inserts_subtrees() { document.apply(transaction).unwrap(); let node = document.node_at_path(&Path(vec![0, 0])).unwrap(); - let data = document.arena.get(node).unwrap().get(); + let data = document.get_node_data(node).unwrap(); assert_eq!(data.node_type, "image"); } -#[test] -fn test_insert_node() { - let node = NodeSubTree::new("text"); - let root_path: Path = vec![0].into(); - let op = DocumentOperation::Insert {path: root_path.clone(),nodes: vec![node.clone()] }; - let mut document = DocumentTree::new(); - document.apply_op(&op).unwrap(); - let node_id = document.node_at_path(&root_path).unwrap(); - - assert!(document.child_at_index_of_path(node_id, 0).is_some()); -} - #[test] fn test_update_nodes() { let mut document = DocumentTree::new(); @@ -117,7 +105,7 @@ fn test_update_nodes() { document.apply(transaction).unwrap(); let node = document.node_at_path(&Path(vec![1])).unwrap(); - let node_data = document.arena.get(node).unwrap().get(); + let node_data = document.get_node_data(node).unwrap(); let is_bold = node_data.attributes.0.get("bolded").unwrap().clone(); assert_eq!(is_bold.unwrap(), "true"); } @@ -141,7 +129,7 @@ fn test_delete_nodes() { }; document.apply(transaction).unwrap(); - let len = document.root.children(&document.arena).fold(0, |count, _| count + 1); + let len = document.number_of_children(); assert_eq!(len, 2); } From ac23f81e24bbebd1eed386f250ddbd95a8cb59f7 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 20:43:06 +0800 Subject: [PATCH 08/10] chore: private the root node --- shared-lib/lib-ot/src/core/document/document.rs | 7 ++++--- .../lib-ot/src/core/document/document_operation.rs | 2 +- shared-lib/lib-ot/src/core/document/node.rs | 9 ++++++--- shared-lib/lib-ot/src/core/document/transaction.rs | 2 +- shared-lib/lib-ot/tests/main.rs | 4 ++-- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index a7e97021d2..4165ff446c 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -3,11 +3,11 @@ use crate::core::{ DocumentOperation, NodeAttributes, NodeData, NodeSubTree, OperationTransform, TextDelta, Transaction, }; use crate::errors::{ErrorBuilder, OTError, OTErrorCode}; -use indextree::{Arena, Children, FollowingSiblings, Node, NodeId}; +use indextree::{Arena, Children, FollowingSiblings, NodeId}; pub struct DocumentTree { arena: Arena, - pub root: NodeId, + root: NodeId, } impl Default for DocumentTree { @@ -19,6 +19,7 @@ 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 } } @@ -104,7 +105,7 @@ impl DocumentTree { /// /// 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.node_type); + /// assert_eq!(inserted_data.node_type, node.note_type); /// ``` pub fn child_from_node_with_index(&self, at_node: NodeId, index: usize) -> Option { let children = at_node.children(&self.arena); diff --git a/shared-lib/lib-ot/src/core/document/document_operation.rs b/shared-lib/lib-ot/src/core/document/document_operation.rs index a1143a1883..6e34c8cb77 100644 --- a/shared-lib/lib-ot/src/core/document/document_operation.rs +++ b/shared-lib/lib-ot/src/core/document/document_operation.rs @@ -169,7 +169,7 @@ mod tests { let insert = DocumentOperation::Insert { path: Path(vec![0, 1]), nodes: vec![NodeSubTree { - node_type: "text".into(), + note_type: "text".into(), attributes: NodeAttributes::new(), delta: None, children: vec![NodeSubTree::new("text")], diff --git a/shared-lib/lib-ot/src/core/document/node.rs b/shared-lib/lib-ot/src/core/document/node.rs index 3aef136c9c..ea62f3f192 100644 --- a/shared-lib/lib-ot/src/core/document/node.rs +++ b/shared-lib/lib-ot/src/core/document/node.rs @@ -20,10 +20,13 @@ impl NodeData { #[derive(Clone, serde::Serialize, serde::Deserialize)] 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, + #[serde(skip_serializing_if = "Vec::is_empty")] pub children: Vec, } @@ -31,7 +34,7 @@ pub struct 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 +43,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(), } diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index 74e7d893bc..1a9314d6f7 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -134,7 +134,7 @@ impl<'a> TransactionBuilder<'a> { }); NodeSubTree { - node_type: node_data.node_type.clone(), + note_type: node_data.node_type.clone(), attributes: node_data.attributes.clone(), delta: node_data.delta.clone(), children, diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 56c7706c69..250708bcdc 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -1,4 +1,4 @@ -use lib_ot::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder}; +use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder}; use lib_ot::errors::OTErrorCode; use std::collections::HashMap; @@ -70,7 +70,7 @@ fn test_inserts_subtrees() { tb.insert_node_at_path( 0, NodeSubTree { - node_type: "text".into(), + note_type: "text".into(), attributes: NodeAttributes::new(), delta: None, children: vec![NodeSubTree::new("image")], From a2918d251f26720d0ce2c5d83b0fb9e124c26f78 Mon Sep 17 00:00:00 2001 From: appflowy Date: Fri, 9 Sep 2022 14:34:40 +0800 Subject: [PATCH 09/10] refactor: refactor transaction builder in rust style --- .../lib-ot/src/core/document/transaction.rs | 45 ++++---- shared-lib/lib-ot/tests/main.rs | 107 +++++++----------- 2 files changed, 64 insertions(+), 88 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index 1a9314d6f7..a4e4a8f759 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -26,7 +26,6 @@ impl<'a> TransactionBuilder<'a> { } } - /// /// /// # Arguments @@ -42,21 +41,19 @@ impl<'a> TransactionBuilder<'a> { /// // 1 -- text_2 /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder}; /// let mut document = DocumentTree::new(); - /// let transaction = { - /// let mut tb = TransactionBuilder::new(&document); - /// tb.insert_nodes_at_path(0,vec![ NodeSubTree::new("text_1"), NodeSubTree::new("text_2")]); - /// tb.finalize() - /// }; + /// 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>(&mut self, path: T, nodes: Vec) { + pub fn insert_nodes_at_path>(self, path: T, nodes: Vec) -> Self { self.push(DocumentOperation::Insert { path: path.into(), nodes, - }); + }) } /// @@ -74,19 +71,17 @@ impl<'a> TransactionBuilder<'a> { /// // |-- text /// use lib_ot::core::{DocumentTree, NodeSubTree, TransactionBuilder}; /// let mut document = DocumentTree::new(); - /// let transaction = { - /// let mut tb = TransactionBuilder::new(&document); - /// tb.insert_node_at_path(0, NodeSubTree::new("text")); - /// tb.finalize() - /// }; + /// let transaction = TransactionBuilder::new(&document) + /// .insert_node_at_path(0, NodeSubTree::new("text")) + /// .finalize(); /// document.apply(transaction).unwrap(); /// ``` /// - pub fn insert_node_at_path>(&mut self, path: T, node: NodeSubTree) { - self.insert_nodes_at_path(path, vec![node]); + pub fn insert_node_at_path>(self, path: T, node: NodeSubTree) -> Self { + self.insert_nodes_at_path(path, vec![node]) } - pub fn update_attributes_at_path(&mut self, path: &Path, attributes: HashMap>) { + pub fn update_attributes_at_path(self, path: &Path, attributes: HashMap>) -> Self { let mut old_attributes: HashMap> = HashMap::new(); let node = self.document.node_at_path(path).unwrap(); let node_data = self.document.get_node_data(node).unwrap(); @@ -107,28 +102,29 @@ impl<'a> TransactionBuilder<'a> { }) } - pub fn delete_node_at_path(&mut self, path: &Path) { - 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: &Path, 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![]; + let mut deleted_nodes = vec![]; for _ in 0..length { deleted_nodes.push(self.get_deleted_nodes(node)); - node = self.document.following_siblings(node).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) -> NodeSubTree { let node_data = self.document.get_node_data(node_id).unwrap(); - let mut children = vec![]; + let mut children = vec![]; self.document.children_from_node(node_id).for_each(|child_id| { children.push(self.get_deleted_nodes(child_id)); }); @@ -141,8 +137,9 @@ impl<'a> TransactionBuilder<'a> { } } - 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 { diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 250708bcdc..070fba3598 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -11,11 +11,10 @@ fn main() { #[test] fn test_documents() { let mut document = DocumentTree::new(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(0, NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(0, NodeSubTree::new("text")) + .finalize(); + document.apply(transaction).unwrap(); assert!(document.node_at_path(0).is_some()); @@ -23,21 +22,17 @@ fn test_documents() { let node_data = document.get_node_data(node).unwrap(); assert_eq!(node_data.node_type, "text"); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.update_attributes_at_path( + let transaction = TransactionBuilder::new(&document) + .update_attributes_at_path( &vec![0].into(), HashMap::from([("subtype".into(), Some("bullet-list".into()))]), - ); - tb.finalize() - }; + ) + .finalize(); document.apply(transaction).unwrap(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.delete_node_at_path(&vec![0].into()); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .delete_node_at_path(&vec![0].into()) + .finalize(); document.apply(transaction).unwrap(); assert!(document.node_at_path(0).is_none()); } @@ -45,29 +40,24 @@ fn test_documents() { #[test] fn test_inserts_nodes() { let mut document = DocumentTree::new(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(0, NodeSubTree::new("text")); - tb.insert_node_at_path(1, NodeSubTree::new("text")); - tb.insert_node_at_path(2, NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(0, NodeSubTree::new("text")) + .insert_node_at_path(1, NodeSubTree::new("text")) + .insert_node_at_path(2, NodeSubTree::new("text")) + .finalize(); document.apply(transaction).unwrap(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(1, NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(1, NodeSubTree::new("text")) + .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_node_at_path( + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path( 0, NodeSubTree { note_type: "text".into(), @@ -75,9 +65,8 @@ fn test_inserts_subtrees() { delta: None, children: vec![NodeSubTree::new("image")], }, - ); - tb.finalize() - }; + ) + .finalize(); document.apply(transaction).unwrap(); let node = document.node_at_path(&Path(vec![0, 0])).unwrap(); @@ -88,20 +77,16 @@ fn test_inserts_subtrees() { #[test] fn test_update_nodes() { let mut document = DocumentTree::new(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(&vec![0], NodeSubTree::new("text")); - tb.insert_node_at_path(&vec![1], NodeSubTree::new("text")); - tb.insert_node_at_path(vec![2], NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(&vec![0], NodeSubTree::new("text")) + .insert_node_at_path(&vec![1], NodeSubTree::new("text")) + .insert_node_at_path(vec![2], NodeSubTree::new("text")) + .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() - }; + let transaction = TransactionBuilder::new(&document) + .update_attributes_at_path(&vec![1].into(), HashMap::from([("bolded".into(), Some("true".into()))])) + .finalize(); document.apply(transaction).unwrap(); let node = document.node_at_path(&Path(vec![1])).unwrap(); @@ -113,20 +98,16 @@ fn test_update_nodes() { #[test] fn test_delete_nodes() { let mut document = DocumentTree::new(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(0, NodeSubTree::new("text")); - tb.insert_node_at_path(1, NodeSubTree::new("text")); - tb.insert_node_at_path(2, NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(0, NodeSubTree::new("text")) + .insert_node_at_path(1, NodeSubTree::new("text")) + .insert_node_at_path(2, NodeSubTree::new("text")) + .finalize(); document.apply(transaction).unwrap(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.delete_node_at_path(&Path(vec![1])); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .delete_node_at_path(&Path(vec![1])) + .finalize(); document.apply(transaction).unwrap(); let len = document.number_of_children(); @@ -136,12 +117,10 @@ fn test_delete_nodes() { #[test] fn test_errors() { let mut document = DocumentTree::new(); - let transaction = { - let mut tb = TransactionBuilder::new(&document); - tb.insert_node_at_path(0, NodeSubTree::new("text")); - tb.insert_node_at_path(100, NodeSubTree::new("text")); - tb.finalize() - }; + let transaction = TransactionBuilder::new(&document) + .insert_node_at_path(0, NodeSubTree::new("text")) + .insert_node_at_path(100, NodeSubTree::new("text")) + .finalize(); let result = document.apply(transaction); assert_eq!(result.err().unwrap().code, OTErrorCode::PathNotFound); } From 8f114e843c093ee257d0793b62e0bfc0d042a4e7 Mon Sep 17 00:00:00 2001 From: appflowy Date: Fri, 9 Sep 2022 15:05:41 +0800 Subject: [PATCH 10/10] chore: replace fold with count --- .../lib-ot/src/core/document/attributes.rs | 27 ++- .../lib-ot/src/core/document/document.rs | 18 +- shared-lib/lib-ot/src/core/document/node.rs | 5 +- .../lib-ot/src/core/document/position.rs | 5 +- .../lib-ot/src/core/document/transaction.rs | 7 +- shared-lib/lib-ot/tests/main.rs | 127 +----------- shared-lib/lib-ot/tests/node/mod.rs | 2 + shared-lib/lib-ot/tests/node/script.rs | 76 ++++++++ shared-lib/lib-ot/tests/node/test.rs | 184 ++++++++++++++++++ 9 files changed, 308 insertions(+), 143 deletions(-) create mode 100644 shared-lib/lib-ot/tests/node/mod.rs create mode 100644 shared-lib/lib-ot/tests/node/script.rs create mode 100644 shared-lib/lib-ot/tests/node/test.rs diff --git a/shared-lib/lib-ot/src/core/document/attributes.rs b/shared-lib/lib-ot/src/core/document/attributes.rs index d9242c67cc..ca5878fb4b 100644 --- a/shared-lib/lib-ot/src/core/document/attributes.rs +++ b/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>); +pub type AttributeMap = HashMap>; + +#[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> = 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()) { diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 4165ff446c..59758c7ca9 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -126,8 +126,18 @@ impl DocumentTree { Some(self.arena.get(node_id)?.get()) } - pub fn number_of_children(&self) -> usize { - self.root.children(&self.arena).fold(0, |count, _| count + 1) + /// + /// # 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) -> 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> { @@ -176,9 +186,7 @@ impl DocumentTree { 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(()); } diff --git a/shared-lib/lib-ot/src/core/document/node.rs b/shared-lib/lib-ot/src/core/document/node.rs index ea62f3f192..9115f656f4 100644 --- a/shared-lib/lib-ot/src/core/document/node.rs +++ b/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,7 +18,7 @@ impl NodeData { } } -#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Serialize, Deserialize, Eq, PartialEq)] pub struct NodeSubTree { #[serde(rename = "type")] pub note_type: String, diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 383581db27..c098096569 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -1,4 +1,4 @@ -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] pub struct Path(pub Vec); @@ -25,7 +25,7 @@ impl std::convert::Into for &usize { impl std::convert::Into for &Path { fn into(self) -> Path { - self.clone() + self.clone() } } @@ -47,7 +47,6 @@ impl From<&[usize]> for Path { } } - impl Path { // delta is default to be 1 pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path { diff --git a/shared-lib/lib-ot/src/core/document/transaction.rs b/shared-lib/lib-ot/src/core/document/transaction.rs index a4e4a8f759..a99ab66dac 100644 --- a/shared-lib/lib-ot/src/core/document/transaction.rs +++ b/shared-lib/lib-ot/src/core/document/transaction.rs @@ -1,7 +1,6 @@ use crate::core::document::position::Path; -use crate::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree}; +use crate::core::{AttributeMap, DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree}; use indextree::NodeId; -use std::collections::HashMap; pub struct Transaction { pub operations: Vec, @@ -81,8 +80,8 @@ impl<'a> TransactionBuilder<'a> { self.insert_nodes_at_path(path, vec![node]) } - pub fn update_attributes_at_path(self, path: &Path, attributes: HashMap>) -> Self { - let mut old_attributes: HashMap> = 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.get_node_data(node).unwrap(); diff --git a/shared-lib/lib-ot/tests/main.rs b/shared-lib/lib-ot/tests/main.rs index 070fba3598..274142d345 100644 --- a/shared-lib/lib-ot/tests/main.rs +++ b/shared-lib/lib-ot/tests/main.rs @@ -1,126 +1 @@ -use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Path, 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 = TransactionBuilder::new(&document) - .insert_node_at_path(0, NodeSubTree::new("text")) - .finalize(); - - document.apply(transaction).unwrap(); - - assert!(document.node_at_path(0).is_some()); - let node = document.node_at_path(0).unwrap(); - let node_data = document.get_node_data(node).unwrap(); - assert_eq!(node_data.node_type, "text"); - - let transaction = TransactionBuilder::new(&document) - .update_attributes_at_path( - &vec![0].into(), - HashMap::from([("subtype".into(), Some("bullet-list".into()))]), - ) - .finalize(); - document.apply(transaction).unwrap(); - - let transaction = TransactionBuilder::new(&document) - .delete_node_at_path(&vec![0].into()) - .finalize(); - document.apply(transaction).unwrap(); - assert!(document.node_at_path(0).is_none()); -} - -#[test] -fn test_inserts_nodes() { - let mut document = DocumentTree::new(); - let transaction = TransactionBuilder::new(&document) - .insert_node_at_path(0, NodeSubTree::new("text")) - .insert_node_at_path(1, NodeSubTree::new("text")) - .insert_node_at_path(2, NodeSubTree::new("text")) - .finalize(); - document.apply(transaction).unwrap(); - - let transaction = TransactionBuilder::new(&document) - .insert_node_at_path(1, NodeSubTree::new("text")) - .finalize(); - document.apply(transaction).unwrap(); -} - -#[test] -fn test_inserts_subtrees() { - let mut document = DocumentTree::new(); - let transaction = TransactionBuilder::new(&document) - .insert_node_at_path( - 0, - NodeSubTree { - note_type: "text".into(), - attributes: NodeAttributes::new(), - delta: None, - children: vec![NodeSubTree::new("image")], - }, - ) - .finalize(); - document.apply(transaction).unwrap(); - - let node = document.node_at_path(&Path(vec![0, 0])).unwrap(); - let data = document.get_node_data(node).unwrap(); - assert_eq!(data.node_type, "image"); -} - -#[test] -fn test_update_nodes() { - let mut document = DocumentTree::new(); - let transaction = TransactionBuilder::new(&document) - .insert_node_at_path(&vec![0], NodeSubTree::new("text")) - .insert_node_at_path(&vec![1], NodeSubTree::new("text")) - .insert_node_at_path(vec![2], NodeSubTree::new("text")) - .finalize(); - document.apply(transaction).unwrap(); - - let transaction = TransactionBuilder::new(&document) - .update_attributes_at_path(&vec![1].into(), HashMap::from([("bolded".into(), Some("true".into()))])) - .finalize(); - document.apply(transaction).unwrap(); - - let node = document.node_at_path(&Path(vec![1])).unwrap(); - let node_data = document.get_node_data(node).unwrap(); - 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 = TransactionBuilder::new(&document) - .insert_node_at_path(0, NodeSubTree::new("text")) - .insert_node_at_path(1, NodeSubTree::new("text")) - .insert_node_at_path(2, NodeSubTree::new("text")) - .finalize(); - document.apply(transaction).unwrap(); - - let transaction = TransactionBuilder::new(&document) - .delete_node_at_path(&Path(vec![1])) - .finalize(); - document.apply(transaction).unwrap(); - - let len = document.number_of_children(); - assert_eq!(len, 2); -} - -#[test] -fn test_errors() { - let mut document = DocumentTree::new(); - let transaction = TransactionBuilder::new(&document) - .insert_node_at_path(0, NodeSubTree::new("text")) - .insert_node_at_path(100, NodeSubTree::new("text")) - .finalize(); - let result = document.apply(transaction); - assert_eq!(result.err().unwrap().code, OTErrorCode::PathNotFound); -} +mod node; diff --git a/shared-lib/lib-ot/tests/node/mod.rs b/shared-lib/lib-ot/tests/node/mod.rs new file mode 100644 index 0000000000..63d424afaf --- /dev/null +++ b/shared-lib/lib-ot/tests/node/mod.rs @@ -0,0 +1,2 @@ +mod script; +mod test; diff --git a/shared-lib/lib-ot/tests/node/script.rs b/shared-lib/lib-ot/tests/node/script.rs new file mode 100644 index 0000000000..392a746e0b --- /dev/null +++ b/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, len: usize }, + AssertNode { path: Path, expected: Option }, +} + +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) { + 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) + } + }, + } + } +} diff --git a/shared-lib/lib-ot/tests/node/test.rs b/shared-lib/lib-ot/tests/node/test.rs new file mode 100644 index 0000000000..d299b08714 --- /dev/null +++ b/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); +}