node_tree.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. use crate::core::document::path::Path;
  2. use crate::core::{Node, NodeAttributes, NodeBodyChangeset, NodeData, NodeOperation, OperationTransform, Transaction};
  3. use crate::errors::{ErrorBuilder, OTError, OTErrorCode};
  4. use indextree::{Arena, Children, FollowingSiblings, NodeId};
  5. pub struct NodeTree {
  6. arena: Arena<NodeData>,
  7. root: NodeId,
  8. }
  9. impl Default for NodeTree {
  10. fn default() -> Self {
  11. Self::new()
  12. }
  13. }
  14. impl NodeTree {
  15. pub fn new() -> NodeTree {
  16. let mut arena = Arena::new();
  17. let root = arena.new_node(NodeData::new("root"));
  18. NodeTree { arena, root }
  19. }
  20. pub fn get_node_data(&self, node_id: NodeId) -> Option<&NodeData> {
  21. Some(self.arena.get(node_id)?.get())
  22. }
  23. ///
  24. /// # Examples
  25. ///
  26. /// ```
  27. /// use lib_ot::core::{NodeOperation, NodeTree, Node, Path};
  28. /// let nodes = vec![Node::new("text".to_string())];
  29. /// let root_path: Path = vec![0].into();
  30. /// let op = NodeOperation::Insert {path: root_path.clone(),nodes };
  31. ///
  32. /// let mut node_tree = NodeTree::new();
  33. /// node_tree.apply_op(&op).unwrap();
  34. /// let node_id = node_tree.node_at_path(&root_path).unwrap();
  35. /// let node_path = node_tree.path_of_node(node_id);
  36. /// debug_assert_eq!(node_path, root_path);
  37. /// ```
  38. pub fn node_at_path<T: Into<Path>>(&self, path: T) -> Option<NodeId> {
  39. let path = path.into();
  40. if path.is_empty() {
  41. return Some(self.root);
  42. }
  43. let mut iterate_node = self.root;
  44. for id in path.iter() {
  45. iterate_node = self.child_from_node_at_index(iterate_node, *id)?;
  46. }
  47. Some(iterate_node)
  48. }
  49. pub fn path_of_node(&self, node_id: NodeId) -> Path {
  50. let mut path = vec![];
  51. let mut current_node = node_id;
  52. // Use .skip(1) on the ancestors iterator to skip the root node.
  53. let mut ancestors = node_id.ancestors(&self.arena).skip(1);
  54. while let Some(parent_node) = ancestors.next() {
  55. let counter = self.index_of_node(parent_node, current_node);
  56. path.push(counter);
  57. current_node = parent_node;
  58. }
  59. Path(path)
  60. }
  61. fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
  62. let mut counter: usize = 0;
  63. let mut iter = parent_node.children(&self.arena);
  64. while let Some(node) = iter.next() {
  65. if node == child_node {
  66. return counter;
  67. }
  68. counter += 1;
  69. }
  70. counter
  71. }
  72. ///
  73. /// # Arguments
  74. ///
  75. /// * `node_id`:
  76. /// * `index`:
  77. ///
  78. /// returns: Option<NodeId>
  79. ///
  80. /// # Examples
  81. ///
  82. /// ```
  83. /// use lib_ot::core::{NodeOperation, NodeTree, Node, Path};
  84. /// let node = Node::new("text".to_string());
  85. /// let inserted_path: Path = vec![0].into();
  86. ///
  87. /// let mut node_tree = NodeTree::new();
  88. /// node_tree.apply_op(&NodeOperation::Insert {path: inserted_path.clone(),nodes: vec![node.clone()] }).unwrap();
  89. ///
  90. /// let inserted_note = node_tree.node_at_path(&inserted_path).unwrap();
  91. /// let inserted_data = node_tree.get_node_data(inserted_note).unwrap();
  92. /// assert_eq!(inserted_data.node_type, node.node_type);
  93. /// ```
  94. pub fn child_from_node_at_index(&self, node_id: NodeId, index: usize) -> Option<NodeId> {
  95. let children = node_id.children(&self.arena);
  96. for (counter, child) in children.enumerate() {
  97. if counter == index {
  98. return Some(child);
  99. }
  100. }
  101. None
  102. }
  103. pub fn children_from_node(&self, node_id: NodeId) -> Children<'_, NodeData> {
  104. node_id.children(&self.arena)
  105. }
  106. ///
  107. /// # Arguments
  108. ///
  109. /// * `node_id`: if the node_is is None, then will use root node_id.
  110. ///
  111. /// returns number of the children of the root node
  112. ///
  113. pub fn number_of_children(&self, node_id: Option<NodeId>) -> usize {
  114. match node_id {
  115. None => self.root.children(&self.arena).count(),
  116. Some(node_id) => node_id.children(&self.arena).count(),
  117. }
  118. }
  119. pub fn following_siblings(&self, node_id: NodeId) -> FollowingSiblings<'_, NodeData> {
  120. node_id.following_siblings(&self.arena)
  121. }
  122. pub fn apply(&mut self, transaction: Transaction) -> Result<(), OTError> {
  123. for op in &transaction.operations {
  124. self.apply_op(op)?;
  125. }
  126. Ok(())
  127. }
  128. pub fn apply_op(&mut self, op: &NodeOperation) -> Result<(), OTError> {
  129. match op {
  130. NodeOperation::Insert { path, nodes } => self.insert_nodes(path, nodes),
  131. NodeOperation::Update { path, attributes, .. } => self.update_node(path, attributes),
  132. NodeOperation::Delete { path, nodes } => self.delete_node(path, nodes),
  133. NodeOperation::EditBody { path, changeset: body } => self.update_body(path, body),
  134. }
  135. }
  136. fn insert_nodes(&mut self, path: &Path, nodes: &[Node]) -> Result<(), OTError> {
  137. debug_assert!(!path.is_empty());
  138. if path.is_empty() {
  139. return Err(OTErrorCode::PathIsEmpty.into());
  140. }
  141. let (parent_path, last_path) = path.split_at(path.0.len() - 1);
  142. let last_index = *last_path.first().unwrap();
  143. let parent_node = self
  144. .node_at_path(parent_path)
  145. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  146. self.insert_nodes_at_index(parent_node, last_index, nodes)
  147. }
  148. fn insert_nodes_at_index(&mut self, parent: NodeId, index: usize, insert_children: &[Node]) -> Result<(), OTError> {
  149. if index == 0 && parent.children(&self.arena).next().is_none() {
  150. self.append_nodes(&parent, insert_children);
  151. return Ok(());
  152. }
  153. if index == parent.children(&self.arena).count() {
  154. self.append_nodes(&parent, insert_children);
  155. return Ok(());
  156. }
  157. let node_to_insert = self
  158. .child_from_node_at_index(parent, index)
  159. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  160. self.insert_subtree_before(&node_to_insert, insert_children);
  161. Ok(())
  162. }
  163. // recursive append the subtrees to the node
  164. fn append_nodes(&mut self, parent: &NodeId, insert_children: &[Node]) {
  165. for child in insert_children {
  166. let child_id = self.arena.new_node(child.into());
  167. parent.append(child_id, &mut self.arena);
  168. self.append_nodes(&child_id, &child.children);
  169. }
  170. }
  171. fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[Node]) {
  172. for child in insert_children {
  173. let child_id = self.arena.new_node(child.into());
  174. before.insert_before(child_id, &mut self.arena);
  175. self.append_nodes(&child_id, &child.children);
  176. }
  177. }
  178. fn update_node(&mut self, path: &Path, attributes: &NodeAttributes) -> Result<(), OTError> {
  179. self.mut_node_at_path(path, |node_data| {
  180. let new_attributes = NodeAttributes::compose(&node_data.attributes, attributes)?;
  181. node_data.attributes = new_attributes;
  182. Ok(())
  183. })
  184. }
  185. fn delete_node(&mut self, path: &Path, nodes: &[Node]) -> Result<(), OTError> {
  186. let mut update_node = self
  187. .node_at_path(path)
  188. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  189. for _ in 0..nodes.len() {
  190. let next = update_node.following_siblings(&self.arena).next();
  191. update_node.remove_subtree(&mut self.arena);
  192. if let Some(next_id) = next {
  193. update_node = next_id;
  194. } else {
  195. break;
  196. }
  197. }
  198. Ok(())
  199. }
  200. fn update_body(&mut self, path: &Path, changeset: &NodeBodyChangeset) -> Result<(), OTError> {
  201. self.mut_node_at_path(path, |node_data| {
  202. node_data.apply_body_changeset(changeset);
  203. Ok(())
  204. })
  205. }
  206. fn mut_node_at_path<F>(&mut self, path: &Path, f: F) -> Result<(), OTError>
  207. where
  208. F: Fn(&mut NodeData) -> Result<(), OTError>,
  209. {
  210. let node_id = self
  211. .node_at_path(path)
  212. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  213. match self.arena.get_mut(node_id) {
  214. None => tracing::warn!("The path: {:?} does not contain any nodes", path),
  215. Some(node) => {
  216. let node_data = node.get_mut();
  217. let _ = f(node_data)?;
  218. }
  219. }
  220. Ok(())
  221. }
  222. }