tree.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. use crate::core::attributes::Attributes;
  2. use crate::core::{Node, NodeBodyChangeset, NodeData, NodeOperation, OperationTransform, Path, Transaction};
  3. use crate::errors::{ErrorBuilder, OTError, OTErrorCode};
  4. use indextree::{Arena, Children, FollowingSiblings, NodeId};
  5. use std::rc::Rc;
  6. use super::NodeOperationList;
  7. ///
  8. pub struct NodeTree {
  9. arena: Arena<Node>,
  10. root: NodeId,
  11. }
  12. impl Default for NodeTree {
  13. fn default() -> Self {
  14. Self::new("root")
  15. }
  16. }
  17. impl NodeTree {
  18. pub fn new(root_name: &str) -> NodeTree {
  19. let mut arena = Arena::new();
  20. let root = arena.new_node(Node::new(root_name));
  21. NodeTree { arena, root }
  22. }
  23. pub fn from_bytes(root_name: &str, bytes: Vec<u8>) -> Result<Self, OTError> {
  24. let operations = NodeOperationList::from_bytes(bytes)?;
  25. Self::from_operations(root_name, operations)
  26. }
  27. pub fn from_operations(root_name: &str, operations: NodeOperationList) -> Result<Self, OTError> {
  28. let mut node_tree = NodeTree::new(root_name);
  29. for operation in operations.into_inner().into_iter() {
  30. let _ = node_tree.apply_op(operation)?;
  31. }
  32. Ok(node_tree)
  33. }
  34. pub fn get_node(&self, node_id: NodeId) -> Option<&Node> {
  35. Some(self.arena.get(node_id)?.get())
  36. }
  37. pub fn get_node_at_path(&self, path: &Path) -> Option<&Node> {
  38. {
  39. let node_id = self.node_id_at_path(path)?;
  40. self.get_node(node_id)
  41. }
  42. }
  43. ///
  44. /// # Examples
  45. ///
  46. /// ```
  47. /// use std::rc::Rc;
  48. /// use lib_ot::core::{NodeOperation, NodeTree, NodeData, Path};
  49. /// let nodes = vec![NodeData::new("text".to_string())];
  50. /// let root_path: Path = vec![0].into();
  51. /// let op = NodeOperation::Insert {path: root_path.clone(),nodes };
  52. ///
  53. /// let mut node_tree = NodeTree::new("root");
  54. /// node_tree.apply_op(Rc::new(op)).unwrap();
  55. /// let node_id = node_tree.node_id_at_path(&root_path).unwrap();
  56. /// let node_path = node_tree.path_from_node_id(node_id);
  57. /// debug_assert_eq!(node_path, root_path);
  58. /// ```
  59. pub fn node_id_at_path<T: Into<Path>>(&self, path: T) -> Option<NodeId> {
  60. let path = path.into();
  61. if path.is_empty() {
  62. return Some(self.root);
  63. }
  64. let mut iterate_node = self.root;
  65. for id in path.iter() {
  66. iterate_node = self.child_from_node_at_index(iterate_node, *id)?;
  67. }
  68. Some(iterate_node)
  69. }
  70. pub fn path_from_node_id(&self, node_id: NodeId) -> Path {
  71. let mut path = vec![];
  72. let mut current_node = node_id;
  73. // Use .skip(1) on the ancestors iterator to skip the root node.
  74. let ancestors = node_id.ancestors(&self.arena).skip(1);
  75. for parent_node in ancestors {
  76. let counter = self.index_of_node(parent_node, current_node);
  77. path.push(counter);
  78. current_node = parent_node;
  79. }
  80. Path(path)
  81. }
  82. fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
  83. let mut counter: usize = 0;
  84. let iter = parent_node.children(&self.arena);
  85. for node in iter {
  86. if node == child_node {
  87. return counter;
  88. }
  89. counter += 1;
  90. }
  91. counter
  92. }
  93. /// Returns the note_id at the position of the tree with id note_id
  94. /// # Arguments
  95. ///
  96. /// * `node_id`: the node id of the child's parent
  97. /// * `index`: index of the node in parent children list
  98. ///
  99. /// returns: Option<NodeId>
  100. ///
  101. /// # Examples
  102. ///
  103. /// ```
  104. /// use std::rc::Rc;
  105. /// use lib_ot::core::{NodeOperation, NodeTree, NodeData, Path};
  106. /// let node_1 = NodeData::new("text".to_string());
  107. /// let inserted_path: Path = vec![0].into();
  108. ///
  109. /// let mut node_tree = NodeTree::new("root");
  110. /// let op = NodeOperation::Insert {path: inserted_path.clone(),nodes: vec![node_1.clone()] };
  111. /// node_tree.apply_op(Rc::new(op)).unwrap();
  112. ///
  113. /// let node_2 = node_tree.get_node_at_path(&inserted_path).unwrap();
  114. /// assert_eq!(node_2.node_type, node_1.node_type);
  115. /// ```
  116. pub fn child_from_node_at_index(&self, node_id: NodeId, index: usize) -> Option<NodeId> {
  117. let children = node_id.children(&self.arena);
  118. for (counter, child) in children.enumerate() {
  119. if counter == index {
  120. return Some(child);
  121. }
  122. }
  123. None
  124. }
  125. /// Returns all children whose parent node id is node_id
  126. ///
  127. /// * `node_id`: the children's parent node id
  128. ///
  129. pub fn children_from_node(&self, node_id: NodeId) -> Children<'_, Node> {
  130. node_id.children(&self.arena)
  131. }
  132. ///
  133. /// # Arguments
  134. ///
  135. /// * `node_id`: if the node_is is None, then will use root node_id.
  136. ///
  137. /// returns number of the children of the root node
  138. ///
  139. pub fn number_of_children(&self, node_id: Option<NodeId>) -> usize {
  140. match node_id {
  141. None => self.root.children(&self.arena).count(),
  142. Some(node_id) => node_id.children(&self.arena).count(),
  143. }
  144. }
  145. pub fn following_siblings(&self, node_id: NodeId) -> FollowingSiblings<'_, Node> {
  146. node_id.following_siblings(&self.arena)
  147. }
  148. pub fn apply_transaction(&mut self, transaction: Transaction) -> Result<(), OTError> {
  149. let operations = transaction.into_operations();
  150. for operation in operations {
  151. self.apply_op(operation)?;
  152. }
  153. Ok(())
  154. }
  155. pub fn apply_op(&mut self, op: Rc<NodeOperation>) -> Result<(), OTError> {
  156. let op = match Rc::try_unwrap(op) {
  157. Ok(op) => op,
  158. Err(op) => op.as_ref().clone(),
  159. };
  160. match op {
  161. NodeOperation::Insert { path, nodes } => self.insert_nodes(&path, nodes),
  162. NodeOperation::UpdateAttributes { path, new, .. } => self.update_attributes(&path, new),
  163. NodeOperation::UpdateBody { path, changeset } => self.update_body(&path, changeset),
  164. NodeOperation::Delete { path, nodes } => self.delete_node(&path, nodes),
  165. }
  166. }
  167. /// Inserts nodes at given path
  168. ///
  169. /// returns error if the path is empty
  170. ///
  171. fn insert_nodes(&mut self, path: &Path, nodes: Vec<NodeData>) -> Result<(), OTError> {
  172. debug_assert!(!path.is_empty());
  173. if path.is_empty() {
  174. return Err(OTErrorCode::PathIsEmpty.into());
  175. }
  176. let (parent_path, last_path) = path.split_at(path.0.len() - 1);
  177. let last_index = *last_path.first().unwrap();
  178. let parent_node = self
  179. .node_id_at_path(parent_path)
  180. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  181. self.insert_nodes_at_index(parent_node, last_index, nodes)
  182. }
  183. /// Inserts nodes before the node with node_id
  184. ///
  185. fn insert_nodes_before(&mut self, node_id: &NodeId, nodes: Vec<NodeData>) {
  186. for node in nodes {
  187. let (node, children) = node.split();
  188. let new_node_id = self.arena.new_node(node);
  189. if node_id.is_removed(&self.arena) {
  190. tracing::warn!("Node:{:?} is remove before insert", node_id);
  191. return;
  192. }
  193. node_id.insert_before(new_node_id, &mut self.arena);
  194. self.append_nodes(&new_node_id, children);
  195. }
  196. }
  197. fn insert_nodes_at_index(&mut self, parent: NodeId, index: usize, nodes: Vec<NodeData>) -> Result<(), OTError> {
  198. if index == 0 && parent.children(&self.arena).next().is_none() {
  199. self.append_nodes(&parent, nodes);
  200. return Ok(());
  201. }
  202. // Append the node to the end of the children list if index greater or equal to the
  203. // length of the children.
  204. if index >= parent.children(&self.arena).count() {
  205. self.append_nodes(&parent, nodes);
  206. return Ok(());
  207. }
  208. let node_to_insert = self
  209. .child_from_node_at_index(parent, index)
  210. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  211. self.insert_nodes_before(&node_to_insert, nodes);
  212. Ok(())
  213. }
  214. fn append_nodes(&mut self, parent: &NodeId, nodes: Vec<NodeData>) {
  215. for node in nodes {
  216. let (node, children) = node.split();
  217. let new_node_id = self.arena.new_node(node);
  218. parent.append(new_node_id, &mut self.arena);
  219. self.append_nodes(&new_node_id, children);
  220. }
  221. }
  222. fn update_attributes(&mut self, path: &Path, attributes: Attributes) -> Result<(), OTError> {
  223. self.mut_node_at_path(path, |node| {
  224. let new_attributes = Attributes::compose(&node.attributes, &attributes)?;
  225. node.attributes = new_attributes;
  226. Ok(())
  227. })
  228. }
  229. fn delete_node(&mut self, path: &Path, nodes: Vec<NodeData>) -> Result<(), OTError> {
  230. let mut update_node = self
  231. .node_id_at_path(path)
  232. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  233. for _ in 0..nodes.len() {
  234. let next = update_node.following_siblings(&self.arena).next();
  235. update_node.remove_subtree(&mut self.arena);
  236. if let Some(next_id) = next {
  237. update_node = next_id;
  238. } else {
  239. break;
  240. }
  241. }
  242. Ok(())
  243. }
  244. fn update_body(&mut self, path: &Path, changeset: NodeBodyChangeset) -> Result<(), OTError> {
  245. self.mut_node_at_path(path, |node| {
  246. node.apply_body_changeset(changeset);
  247. Ok(())
  248. })
  249. }
  250. fn mut_node_at_path<F>(&mut self, path: &Path, f: F) -> Result<(), OTError>
  251. where
  252. F: FnOnce(&mut Node) -> Result<(), OTError>,
  253. {
  254. let node_id = self
  255. .node_id_at_path(path)
  256. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  257. match self.arena.get_mut(node_id) {
  258. None => tracing::warn!("The path: {:?} does not contain any nodes", path),
  259. Some(node) => {
  260. let node = node.get_mut();
  261. let _ = f(node)?;
  262. }
  263. }
  264. Ok(())
  265. }
  266. }