operation.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. use crate::core::interval::Interval;
  2. use crate::core::ot_str::OTString;
  3. use crate::errors::OTError;
  4. use serde::{Deserialize, Serialize, __private::Formatter};
  5. use std::fmt::Display;
  6. use std::{
  7. cmp::min,
  8. fmt,
  9. fmt::Debug,
  10. ops::{Deref, DerefMut},
  11. };
  12. pub trait OperationTransform {
  13. /// Merges the operation with `other` into one operation while preserving
  14. /// the changes of both.
  15. ///
  16. /// # Arguments
  17. ///
  18. /// * `other`: The delta gonna to merge.
  19. ///
  20. /// # Examples
  21. ///
  22. /// ```
  23. /// use lib_ot::core::{OperationTransform, TextDeltaBuilder};
  24. /// let document = TextDeltaBuilder::new().build();
  25. /// let delta = TextDeltaBuilder::new().insert("abc").build();
  26. /// let new_document = document.compose(&delta).unwrap();
  27. /// assert_eq!(new_document.content_str().unwrap(), "abc".to_owned());
  28. /// ```
  29. fn compose(&self, other: &Self) -> Result<Self, OTError>
  30. where
  31. Self: Sized;
  32. /// Transforms two operations a and b that happened concurrently and
  33. /// produces two operations a' and b'.
  34. /// (a', b') = a.transform(b)
  35. /// a.compose(b') = b.compose(a')
  36. ///
  37. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  38. where
  39. Self: Sized;
  40. /// Returns the invert delta from the other. It can be used to do the undo operation.
  41. ///
  42. /// # Arguments
  43. ///
  44. /// * `other`: Generate the undo delta for [Other]. [Other] can compose the undo delta to return
  45. /// to the previous state.
  46. ///
  47. /// # Examples
  48. ///
  49. /// ```
  50. /// use lib_ot::core::{OperationTransform, TextDeltaBuilder};
  51. /// let original_document = TextDeltaBuilder::new().build();
  52. /// let delta = TextDeltaBuilder::new().insert("abc").build();
  53. ///
  54. /// let undo_delta = delta.invert(&original_document);
  55. /// let new_document = original_document.compose(&delta).unwrap();
  56. /// let document = new_document.compose(&undo_delta).unwrap();
  57. ///
  58. /// assert_eq!(original_document, document);
  59. ///
  60. /// ```
  61. fn invert(&self, other: &Self) -> Self;
  62. }
  63. /// Each operation can carry attributes. For example, the [RichTextAttributes] has a list of key/value attributes.
  64. /// Such as { bold: true, italic: true }.
  65. ///
  66. ///Because [Operation] is generic over the T, so you must specify the T. For example, the [TextDelta] uses
  67. ///[PhantomAttributes] as the T. [PhantomAttributes] does nothing, just a phantom.
  68. ///
  69. pub trait Attributes: Default + Display + Eq + PartialEq + Clone + Debug + OperationTransform {
  70. fn is_empty(&self) -> bool {
  71. true
  72. }
  73. /// Remove the empty attribute which value is None.
  74. fn remove_empty(&mut self) {
  75. // Do nothing
  76. }
  77. fn extend_other(&mut self, _other: Self) {
  78. // Do nothing
  79. }
  80. }
  81. /// [Operation] consists of three types.
  82. /// * Delete
  83. /// * Retain
  84. /// * Insert
  85. ///
  86. /// You could check [this](https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/backend/delta) out for more information.
  87. ///
  88. /// The [T] should support serde if you want to serialize/deserialize the operation
  89. /// to json string. You could check out the operation_serde.rs for more information.
  90. ///
  91. #[derive(Debug, Clone, Eq, PartialEq)]
  92. pub enum Operation<T: Attributes> {
  93. Delete(usize),
  94. Retain(Retain<T>),
  95. Insert(Insert<T>),
  96. }
  97. impl<T> Operation<T>
  98. where
  99. T: Attributes,
  100. {
  101. pub fn delete(n: usize) -> Self {
  102. Self::Delete(n)
  103. }
  104. /// Create a [Retain] operation with the given attributes
  105. pub fn retain_with_attributes(n: usize, attributes: T) -> Self {
  106. Self::Retain(Retain { n, attributes })
  107. }
  108. /// Create a [Retain] operation without attributes
  109. pub fn retain(n: usize) -> Self {
  110. Self::Retain(Retain {
  111. n,
  112. attributes: T::default(),
  113. })
  114. }
  115. /// Create a [Insert] operation with the given attributes
  116. pub fn insert_with_attributes(s: &str, attributes: T) -> Self {
  117. Self::Insert(Insert {
  118. s: OTString::from(s),
  119. attributes,
  120. })
  121. }
  122. /// Create a [Insert] operation without attributes
  123. pub fn insert(s: &str) -> Self {
  124. Self::Insert(Insert {
  125. s: OTString::from(s),
  126. attributes: T::default(),
  127. })
  128. }
  129. /// Return the String if the operation is [Insert] operation, otherwise return the empty string.
  130. pub fn get_data(&self) -> &str {
  131. match self {
  132. Operation::Delete(_) => "",
  133. Operation::Retain(_) => "",
  134. Operation::Insert(insert) => &insert.s,
  135. }
  136. }
  137. pub fn get_attributes(&self) -> T {
  138. match self {
  139. Operation::Delete(_) => T::default(),
  140. Operation::Retain(retain) => retain.attributes.clone(),
  141. Operation::Insert(insert) => insert.attributes.clone(),
  142. }
  143. }
  144. pub fn set_attributes(&mut self, attributes: T) {
  145. match self {
  146. Operation::Delete(_) => log::error!("Delete should not contains attributes"),
  147. Operation::Retain(retain) => retain.attributes = attributes,
  148. Operation::Insert(insert) => insert.attributes = attributes,
  149. }
  150. }
  151. pub fn has_attribute(&self) -> bool {
  152. !self.get_attributes().is_empty()
  153. }
  154. pub fn len(&self) -> usize {
  155. match self {
  156. Operation::Delete(n) => *n,
  157. Operation::Retain(r) => r.n,
  158. Operation::Insert(i) => i.utf16_size(),
  159. }
  160. }
  161. pub fn is_empty(&self) -> bool {
  162. self.len() == 0
  163. }
  164. #[allow(dead_code)]
  165. pub fn split(&self, index: usize) -> (Option<Operation<T>>, Option<Operation<T>>) {
  166. debug_assert!(index < self.len());
  167. let left;
  168. let right;
  169. match self {
  170. Operation::Delete(n) => {
  171. left = Some(Operation::<T>::delete(index));
  172. right = Some(Operation::<T>::delete(*n - index));
  173. }
  174. Operation::Retain(retain) => {
  175. left = Some(Operation::<T>::delete(index));
  176. right = Some(Operation::<T>::delete(retain.n - index));
  177. }
  178. Operation::Insert(insert) => {
  179. let attributes = self.get_attributes();
  180. left = Some(Operation::<T>::insert_with_attributes(
  181. &insert.s[0..index],
  182. attributes.clone(),
  183. ));
  184. right = Some(Operation::<T>::insert_with_attributes(
  185. &insert.s[index..insert.utf16_size()],
  186. attributes,
  187. ));
  188. }
  189. }
  190. (left, right)
  191. }
  192. /// Returns an operation with the specified width.
  193. /// # Arguments
  194. ///
  195. /// * `interval`: Specify the shrink width of the operation.
  196. ///
  197. /// # Examples
  198. ///
  199. /// ```
  200. /// use lib_ot::core::{Interval, Operation, PhantomAttributes};
  201. /// let operation = Operation::<PhantomAttributes>::insert("1234");
  202. ///
  203. /// let op1 = operation.shrink(Interval::new(0,3)).unwrap();
  204. /// assert_eq!(op1 , Operation::insert("123"));
  205. ///
  206. /// let op2= operation.shrink(Interval::new(3,4)).unwrap();
  207. /// assert_eq!(op2, Operation::insert("4"));
  208. /// ```
  209. pub fn shrink(&self, interval: Interval) -> Option<Operation<T>> {
  210. let op = match self {
  211. Operation::Delete(n) => Operation::delete(min(*n, interval.size())),
  212. Operation::Retain(retain) => {
  213. Operation::retain_with_attributes(min(retain.n, interval.size()), retain.attributes.clone())
  214. }
  215. Operation::Insert(insert) => {
  216. if interval.start > insert.utf16_size() {
  217. Operation::insert("")
  218. } else {
  219. let s = insert.s.sub_str(interval).unwrap_or_else(|| "".to_owned());
  220. Operation::insert_with_attributes(&s, insert.attributes.clone())
  221. }
  222. }
  223. };
  224. match op.is_empty() {
  225. true => None,
  226. false => Some(op),
  227. }
  228. }
  229. pub fn is_delete(&self) -> bool {
  230. if let Operation::Delete(_) = self {
  231. return true;
  232. }
  233. false
  234. }
  235. pub fn is_insert(&self) -> bool {
  236. if let Operation::Insert(_) = self {
  237. return true;
  238. }
  239. false
  240. }
  241. pub fn is_retain(&self) -> bool {
  242. if let Operation::Retain(_) = self {
  243. return true;
  244. }
  245. false
  246. }
  247. pub fn is_plain(&self) -> bool {
  248. match self {
  249. Operation::Delete(_) => true,
  250. Operation::Retain(retain) => retain.is_plain(),
  251. Operation::Insert(insert) => insert.is_plain(),
  252. }
  253. }
  254. }
  255. impl<T> fmt::Display for Operation<T>
  256. where
  257. T: Attributes,
  258. {
  259. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  260. f.write_str("{")?;
  261. match self {
  262. Operation::Delete(n) => {
  263. f.write_fmt(format_args!("delete: {}", n))?;
  264. }
  265. Operation::Retain(r) => {
  266. f.write_fmt(format_args!("{}", r))?;
  267. }
  268. Operation::Insert(i) => {
  269. f.write_fmt(format_args!("{}", i))?;
  270. }
  271. }
  272. f.write_str("}")?;
  273. Ok(())
  274. }
  275. }
  276. #[derive(Clone, Debug, Eq, PartialEq)]
  277. pub struct Retain<T: Attributes> {
  278. pub n: usize,
  279. pub attributes: T,
  280. }
  281. impl<T> fmt::Display for Retain<T>
  282. where
  283. T: Attributes,
  284. {
  285. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  286. if self.attributes.is_empty() {
  287. f.write_fmt(format_args!("retain: {}", self.n))
  288. } else {
  289. f.write_fmt(format_args!("retain: {}, attributes: {}", self.n, self.attributes))
  290. }
  291. }
  292. }
  293. impl<T> Retain<T>
  294. where
  295. T: Attributes,
  296. {
  297. pub fn merge_or_new(&mut self, n: usize, attributes: T) -> Option<Operation<T>> {
  298. // tracing::trace!(
  299. // "merge_retain_or_new_op: len: {:?}, l: {} - r: {}",
  300. // n,
  301. // self.attributes,
  302. // attributes
  303. // );
  304. if self.attributes == attributes {
  305. self.n += n;
  306. None
  307. } else {
  308. Some(Operation::retain_with_attributes(n, attributes))
  309. }
  310. }
  311. pub fn is_plain(&self) -> bool {
  312. self.attributes.is_empty()
  313. }
  314. }
  315. impl<T> std::convert::From<usize> for Retain<T>
  316. where
  317. T: Attributes,
  318. {
  319. fn from(n: usize) -> Self {
  320. Retain {
  321. n,
  322. attributes: T::default(),
  323. }
  324. }
  325. }
  326. impl<T> Deref for Retain<T>
  327. where
  328. T: Attributes,
  329. {
  330. type Target = usize;
  331. fn deref(&self) -> &Self::Target {
  332. &self.n
  333. }
  334. }
  335. impl<T> DerefMut for Retain<T>
  336. where
  337. T: Attributes,
  338. {
  339. fn deref_mut(&mut self) -> &mut Self::Target {
  340. &mut self.n
  341. }
  342. }
  343. #[derive(Clone, Debug, Eq, PartialEq)]
  344. pub struct Insert<T: Attributes> {
  345. pub s: OTString,
  346. pub attributes: T,
  347. }
  348. impl<T> fmt::Display for Insert<T>
  349. where
  350. T: Attributes,
  351. {
  352. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  353. let mut s = self.s.clone();
  354. if s.ends_with('\n') {
  355. s.pop();
  356. if s.is_empty() {
  357. s = "new_line".into();
  358. }
  359. }
  360. if self.attributes.is_empty() {
  361. f.write_fmt(format_args!("insert: {}", s))
  362. } else {
  363. f.write_fmt(format_args!("insert: {}, attributes: {}", s, self.attributes))
  364. }
  365. }
  366. }
  367. impl<T> Insert<T>
  368. where
  369. T: Attributes,
  370. {
  371. pub fn utf16_size(&self) -> usize {
  372. self.s.utf16_len()
  373. }
  374. pub fn merge_or_new_op(&mut self, s: &str, attributes: T) -> Option<Operation<T>> {
  375. if self.attributes == attributes {
  376. self.s += s;
  377. None
  378. } else {
  379. Some(Operation::<T>::insert_with_attributes(s, attributes))
  380. }
  381. }
  382. pub fn is_plain(&self) -> bool {
  383. self.attributes.is_empty()
  384. }
  385. }
  386. impl<T> std::convert::From<String> for Insert<T>
  387. where
  388. T: Attributes,
  389. {
  390. fn from(s: String) -> Self {
  391. Insert {
  392. s: s.into(),
  393. attributes: T::default(),
  394. }
  395. }
  396. }
  397. impl<T> std::convert::From<&str> for Insert<T>
  398. where
  399. T: Attributes,
  400. {
  401. fn from(s: &str) -> Self {
  402. Insert::from(s.to_owned())
  403. }
  404. }
  405. impl<T> std::convert::From<OTString> for Insert<T>
  406. where
  407. T: Attributes,
  408. {
  409. fn from(s: OTString) -> Self {
  410. Insert {
  411. s,
  412. attributes: T::default(),
  413. }
  414. }
  415. }
  416. #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)]
  417. pub struct PhantomAttributes();
  418. impl fmt::Display for PhantomAttributes {
  419. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  420. f.write_str("PhantomAttributes")
  421. }
  422. }
  423. impl Attributes for PhantomAttributes {}
  424. impl OperationTransform for PhantomAttributes {
  425. fn compose(&self, _other: &Self) -> Result<Self, OTError> {
  426. Ok(self.clone())
  427. }
  428. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError> {
  429. Ok((self.clone(), other.clone()))
  430. }
  431. fn invert(&self, _other: &Self) -> Self {
  432. self.clone()
  433. }
  434. }