document.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. use crate::core::document::position::Position;
  2. use crate::core::{
  3. DocumentOperation, NodeAttributes, NodeData, NodeSubTree, OperationTransform, TextDelta, Transaction,
  4. };
  5. use crate::errors::{ErrorBuilder, OTError, OTErrorCode};
  6. use indextree::{Arena, NodeId};
  7. pub struct DocumentTree {
  8. pub arena: Arena<NodeData>,
  9. pub root: NodeId,
  10. }
  11. impl Default for DocumentTree {
  12. fn default() -> Self {
  13. Self::new()
  14. }
  15. }
  16. impl DocumentTree {
  17. pub fn new() -> DocumentTree {
  18. let mut arena = Arena::new();
  19. let root = arena.new_node(NodeData::new("root"));
  20. DocumentTree { arena, root }
  21. }
  22. pub fn node_at_path(&self, position: &Position) -> Option<NodeId> {
  23. if position.is_empty() {
  24. return Some(self.root);
  25. }
  26. let mut iterate_node = self.root;
  27. for id in &position.0 {
  28. let child = self.child_at_index_of_path(iterate_node, *id);
  29. iterate_node = match child {
  30. Some(node) => node,
  31. None => return None,
  32. };
  33. }
  34. Some(iterate_node)
  35. }
  36. pub fn path_of_node(&self, node_id: NodeId) -> Position {
  37. let mut path: Vec<usize> = Vec::new();
  38. let mut ancestors = node_id.ancestors(&self.arena);
  39. let mut current_node = node_id;
  40. let mut parent = ancestors.next();
  41. while parent.is_some() {
  42. let parent_node = parent.unwrap();
  43. let counter = self.index_of_node(parent_node, current_node);
  44. path.push(counter);
  45. current_node = parent_node;
  46. parent = ancestors.next();
  47. }
  48. Position(path)
  49. }
  50. fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
  51. let mut counter: usize = 0;
  52. let mut children_iterator = parent_node.children(&self.arena);
  53. let mut node = children_iterator.next();
  54. while node.is_some() {
  55. if node.unwrap() == child_node {
  56. return counter;
  57. }
  58. node = children_iterator.next();
  59. counter += 1;
  60. }
  61. counter
  62. }
  63. fn child_at_index_of_path(&self, at_node: NodeId, index: usize) -> Option<NodeId> {
  64. let children = at_node.children(&self.arena);
  65. for (counter, child) in children.enumerate() {
  66. if counter == index {
  67. return Some(child);
  68. }
  69. }
  70. None
  71. }
  72. pub fn apply(&mut self, transaction: Transaction) -> Result<(), OTError> {
  73. for op in &transaction.operations {
  74. self.apply_op(op)?;
  75. }
  76. Ok(())
  77. }
  78. fn apply_op(&mut self, op: &DocumentOperation) -> Result<(), OTError> {
  79. match op {
  80. DocumentOperation::Insert { path, nodes } => self.apply_insert(path, nodes),
  81. DocumentOperation::Update { path, attributes, .. } => self.apply_update(path, attributes),
  82. DocumentOperation::Delete { path, nodes } => self.apply_delete(path, nodes.len()),
  83. DocumentOperation::TextEdit { path, delta, .. } => self.apply_text_edit(path, delta),
  84. }
  85. }
  86. fn apply_insert(&mut self, path: &Position, nodes: &[Box<NodeSubTree>]) -> Result<(), OTError> {
  87. let parent_path = &path.0[0..(path.0.len() - 1)];
  88. let last_index = path.0[path.0.len() - 1];
  89. let parent_node = self
  90. .node_at_path(&Position(parent_path.to_vec()))
  91. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  92. self.insert_child_at_index(parent_node, last_index, nodes.as_ref())
  93. }
  94. fn insert_child_at_index(
  95. &mut self,
  96. parent: NodeId,
  97. index: usize,
  98. insert_children: &[Box<NodeSubTree>],
  99. ) -> Result<(), OTError> {
  100. if index == 0 && parent.children(&self.arena).next().is_none() {
  101. self.append_subtree(&parent, insert_children);
  102. return Ok(());
  103. }
  104. let children_length = parent.children(&self.arena).fold(0, |counter, _| counter + 1);
  105. if index == children_length {
  106. self.append_subtree(&parent, insert_children);
  107. return Ok(());
  108. }
  109. let node_to_insert = self
  110. .child_at_index_of_path(parent, index)
  111. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  112. self.insert_subtree_before(&node_to_insert, insert_children);
  113. Ok(())
  114. }
  115. // recursive append the subtrees to the node
  116. fn append_subtree(&mut self, parent: &NodeId, insert_children: &[Box<NodeSubTree>]) {
  117. for child in insert_children {
  118. let child_id = self.arena.new_node(child.to_node_data());
  119. parent.append(child_id, &mut self.arena);
  120. self.append_subtree(&child_id, child.children.as_ref());
  121. }
  122. }
  123. fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[Box<NodeSubTree>]) {
  124. for child in insert_children {
  125. let child_id = self.arena.new_node(child.to_node_data());
  126. before.insert_before(child_id, &mut self.arena);
  127. self.append_subtree(&child_id, child.children.as_ref());
  128. }
  129. }
  130. fn apply_update(&mut self, path: &Position, attributes: &NodeAttributes) -> Result<(), OTError> {
  131. let update_node = self
  132. .node_at_path(path)
  133. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  134. let node_data = self.arena.get_mut(update_node).unwrap();
  135. let new_node = {
  136. let old_attributes = &node_data.get().attributes;
  137. let new_attributes = NodeAttributes::compose(old_attributes, attributes);
  138. NodeData {
  139. attributes: new_attributes,
  140. ..node_data.get().clone()
  141. }
  142. };
  143. *node_data.get_mut() = new_node;
  144. Ok(())
  145. }
  146. fn apply_delete(&mut self, path: &Position, len: usize) -> Result<(), OTError> {
  147. let mut update_node = self
  148. .node_at_path(path)
  149. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  150. for _ in 0..len {
  151. let next = update_node.following_siblings(&self.arena).next();
  152. update_node.remove_subtree(&mut self.arena);
  153. if let Some(next_id) = next {
  154. update_node = next_id;
  155. } else {
  156. break;
  157. }
  158. }
  159. Ok(())
  160. }
  161. fn apply_text_edit(&mut self, path: &Position, delta: &TextDelta) -> Result<(), OTError> {
  162. let edit_node = self
  163. .node_at_path(path)
  164. .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
  165. let node_data = self.arena.get_mut(edit_node).unwrap();
  166. let new_delta = if let Some(old_delta) = &node_data.get().delta {
  167. Some(old_delta.compose(delta)?)
  168. } else {
  169. None
  170. };
  171. if let Some(new_delta) = new_delta {
  172. *node_data.get_mut() = NodeData {
  173. delta: Some(new_delta),
  174. ..node_data.get().clone()
  175. };
  176. };
  177. Ok(())
  178. }
  179. }