node.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. use super::node_serde::*;
  2. use crate::core::attributes::{AttributeHashMap, AttributeKey, AttributeValue};
  3. use crate::core::NodeBody::Delta;
  4. use crate::core::OperationTransform;
  5. use crate::errors::OTError;
  6. use crate::text_delta::TextOperations;
  7. use serde::{Deserialize, Serialize};
  8. #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
  9. pub struct NodeData {
  10. #[serde(rename = "type")]
  11. pub node_type: String,
  12. #[serde(skip_serializing_if = "AttributeHashMap::is_empty")]
  13. #[serde(default)]
  14. pub attributes: AttributeHashMap,
  15. #[serde(serialize_with = "serialize_body")]
  16. #[serde(deserialize_with = "deserialize_body")]
  17. #[serde(skip_serializing_if = "NodeBody::is_empty")]
  18. #[serde(default)]
  19. pub body: NodeBody,
  20. #[serde(skip_serializing_if = "Vec::is_empty")]
  21. #[serde(default)]
  22. pub children: Vec<NodeData>,
  23. }
  24. impl NodeData {
  25. pub fn new<T: ToString>(node_type: T) -> NodeData {
  26. NodeData {
  27. node_type: node_type.to_string(),
  28. ..Default::default()
  29. }
  30. }
  31. pub fn split(self) -> (Node, Vec<NodeData>) {
  32. let node = Node {
  33. node_type: self.node_type,
  34. body: self.body,
  35. attributes: self.attributes,
  36. };
  37. (node, self.children)
  38. }
  39. }
  40. /// Builder for [`NodeData`]
  41. pub struct NodeDataBuilder {
  42. node: NodeData,
  43. }
  44. impl NodeDataBuilder {
  45. pub fn new<T: ToString>(node_type: T) -> Self {
  46. Self {
  47. node: NodeData::new(node_type.to_string()),
  48. }
  49. }
  50. /// Appends a new node to the end of the builder's node children.
  51. pub fn add_node(mut self, node: NodeData) -> Self {
  52. self.node.children.push(node);
  53. self
  54. }
  55. /// Inserts attributes to the builder's node.
  56. ///
  57. /// The attributes will be replace if they shared the same key
  58. pub fn insert_attribute(mut self, key: AttributeKey, value: AttributeValue) -> Self {
  59. self.node.attributes.insert(key, value);
  60. self
  61. }
  62. /// Inserts a body to the builder's node
  63. pub fn insert_body(mut self, body: NodeBody) -> Self {
  64. self.node.body = body;
  65. self
  66. }
  67. /// Returns the builder's node
  68. pub fn build(self) -> NodeData {
  69. self.node
  70. }
  71. }
  72. /// NodeBody represents as the node's data.
  73. ///
  74. /// For the moment, the NodeBody can be Empty or Delta. We can extend
  75. /// the NodeBody by adding a new enum type.
  76. ///
  77. /// The NodeBody implements the [`OperationTransform`] trait which means it can perform
  78. /// compose, transform and invert.
  79. ///
  80. #[derive(Debug, Clone, PartialEq, Eq)]
  81. pub enum NodeBody {
  82. Empty,
  83. Delta(TextOperations),
  84. }
  85. impl std::default::Default for NodeBody {
  86. fn default() -> Self {
  87. NodeBody::Empty
  88. }
  89. }
  90. impl NodeBody {
  91. fn is_empty(&self) -> bool {
  92. matches!(self, NodeBody::Empty)
  93. }
  94. }
  95. impl OperationTransform for NodeBody {
  96. /// Only the same enum variant can perform the compose operation.
  97. fn compose(&self, other: &Self) -> Result<Self, OTError>
  98. where
  99. Self: Sized,
  100. {
  101. match (self, other) {
  102. (Delta(a), Delta(b)) => a.compose(b).map(Delta),
  103. (NodeBody::Empty, NodeBody::Empty) => Ok(NodeBody::Empty),
  104. (l, r) => {
  105. let msg = format!("{:?} can not compose {:?}", l, r);
  106. Err(OTError::internal().context(msg))
  107. }
  108. }
  109. }
  110. /// Only the same enum variant can perform the transform operation.
  111. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  112. where
  113. Self: Sized,
  114. {
  115. match (self, other) {
  116. (Delta(l), Delta(r)) => l.transform(r).map(|(ta, tb)| (Delta(ta), Delta(tb))),
  117. (NodeBody::Empty, NodeBody::Empty) => Ok((NodeBody::Empty, NodeBody::Empty)),
  118. (l, r) => {
  119. let msg = format!("{:?} can not compose {:?}", l, r);
  120. Err(OTError::internal().context(msg))
  121. }
  122. }
  123. }
  124. /// Only the same enum variant can perform the invert operation.
  125. fn invert(&self, other: &Self) -> Self {
  126. match (self, other) {
  127. (Delta(l), Delta(r)) => Delta(l.invert(r)),
  128. (NodeBody::Empty, NodeBody::Empty) => NodeBody::Empty,
  129. (l, r) => {
  130. tracing::error!("{:?} can not compose {:?}", l, r);
  131. l.clone()
  132. }
  133. }
  134. }
  135. }
  136. /// Represents the changeset of the [`NodeBody`]
  137. ///
  138. /// Each NodeBody except the Empty should have its corresponding changeset variant.
  139. #[derive(Debug, Clone, Serialize, Deserialize)]
  140. #[serde(rename_all = "snake_case")]
  141. pub enum NodeBodyChangeset {
  142. Delta {
  143. delta: TextOperations,
  144. inverted: TextOperations,
  145. },
  146. }
  147. impl NodeBodyChangeset {
  148. pub fn inverted(&self) -> NodeBodyChangeset {
  149. match self {
  150. NodeBodyChangeset::Delta { delta, inverted } => NodeBodyChangeset::Delta {
  151. delta: inverted.clone(),
  152. inverted: delta.clone(),
  153. },
  154. }
  155. }
  156. }
  157. /// [`Node`] represents as a leaf in the [`NodeTree`].
  158. ///
  159. #[derive(Clone, Eq, PartialEq, Debug)]
  160. pub struct Node {
  161. pub node_type: String,
  162. pub body: NodeBody,
  163. pub attributes: AttributeHashMap,
  164. }
  165. impl Node {
  166. pub fn new(node_type: &str) -> Node {
  167. Node {
  168. node_type: node_type.into(),
  169. attributes: AttributeHashMap::new(),
  170. body: NodeBody::Empty,
  171. }
  172. }
  173. pub fn apply_body_changeset(&mut self, changeset: NodeBodyChangeset) {
  174. match changeset {
  175. NodeBodyChangeset::Delta { delta, inverted: _ } => match self.body.compose(&Delta(delta)) {
  176. Ok(new_body) => self.body = new_body,
  177. Err(e) => tracing::error!("{:?}", e),
  178. },
  179. }
  180. }
  181. }
  182. impl std::convert::From<NodeData> for Node {
  183. fn from(node: NodeData) -> Self {
  184. Self {
  185. node_type: node.node_type,
  186. attributes: node.attributes,
  187. body: node.body,
  188. }
  189. }
  190. }
  191. impl std::convert::From<&NodeData> for Node {
  192. fn from(node: &NodeData) -> Self {
  193. Self {
  194. node_type: node.node_type.clone(),
  195. attributes: node.attributes.clone(),
  196. body: node.body.clone(),
  197. }
  198. }
  199. }