node.rs 6.1 KB

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