operation.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. use crate::{
  2. core::{FlowyStr, Interval, OpBuilder, OperationTransformable},
  3. rich_text::{RichTextAttribute, RichTextAttributes},
  4. };
  5. use serde::__private::Formatter;
  6. use std::{
  7. cmp::min,
  8. fmt,
  9. fmt::Debug,
  10. ops::{Deref, DerefMut},
  11. };
  12. pub trait Attributes: fmt::Display + Eq + PartialEq + Default + Clone + Debug + OperationTransformable {
  13. fn is_empty(&self) -> bool;
  14. // Remove the empty attribute which value is None.
  15. fn remove_empty(&mut self);
  16. fn extend_other(&mut self, other: Self);
  17. }
  18. pub type RichTextOperation = Operation<RichTextAttributes>;
  19. impl RichTextOperation {
  20. pub fn contain_attribute(&self, attribute: &RichTextAttribute) -> bool {
  21. self.get_attributes().contains_key(&attribute.key)
  22. }
  23. }
  24. #[derive(Debug, Clone, Eq, PartialEq)]
  25. pub enum Operation<T: Attributes> {
  26. Delete(usize),
  27. Retain(Retain<T>),
  28. Insert(Insert<T>),
  29. }
  30. impl<T> Operation<T>
  31. where
  32. T: Attributes,
  33. {
  34. pub fn get_data(&self) -> &str {
  35. match self {
  36. Operation::Delete(_) => "",
  37. Operation::Retain(_) => "",
  38. Operation::Insert(insert) => &insert.s,
  39. }
  40. }
  41. pub fn get_attributes(&self) -> T {
  42. match self {
  43. Operation::Delete(_) => T::default(),
  44. Operation::Retain(retain) => retain.attributes.clone(),
  45. Operation::Insert(insert) => insert.attributes.clone(),
  46. }
  47. }
  48. pub fn set_attributes(&mut self, attributes: T) {
  49. match self {
  50. Operation::Delete(_) => log::error!("Delete should not contains attributes"),
  51. Operation::Retain(retain) => retain.attributes = attributes,
  52. Operation::Insert(insert) => insert.attributes = attributes,
  53. }
  54. }
  55. pub fn has_attribute(&self) -> bool { !self.get_attributes().is_empty() }
  56. pub fn len(&self) -> usize {
  57. match self {
  58. Operation::Delete(n) => *n,
  59. Operation::Retain(r) => r.n,
  60. Operation::Insert(i) => i.count_of_utf16_code_units(),
  61. }
  62. }
  63. pub fn is_empty(&self) -> bool { self.len() == 0 }
  64. #[allow(dead_code)]
  65. pub fn split(&self, index: usize) -> (Option<Operation<T>>, Option<Operation<T>>) {
  66. debug_assert!(index < self.len());
  67. let left;
  68. let right;
  69. match self {
  70. Operation::Delete(n) => {
  71. left = Some(OpBuilder::<T>::delete(index).build());
  72. right = Some(OpBuilder::<T>::delete(*n - index).build());
  73. },
  74. Operation::Retain(retain) => {
  75. left = Some(OpBuilder::<T>::delete(index).build());
  76. right = Some(OpBuilder::<T>::delete(retain.n - index).build());
  77. },
  78. Operation::Insert(insert) => {
  79. let attributes = self.get_attributes();
  80. left = Some(
  81. OpBuilder::<T>::insert(&insert.s[0..index])
  82. .attributes(attributes.clone())
  83. .build(),
  84. );
  85. right = Some(
  86. OpBuilder::<T>::insert(&insert.s[index..insert.count_of_utf16_code_units()])
  87. .attributes(attributes)
  88. .build(),
  89. );
  90. },
  91. }
  92. (left, right)
  93. }
  94. pub fn shrink(&self, interval: Interval) -> Option<Operation<T>> {
  95. let op = match self {
  96. Operation::Delete(n) => OpBuilder::delete(min(*n, interval.size())).build(),
  97. Operation::Retain(retain) => OpBuilder::retain(min(retain.n, interval.size()))
  98. .attributes(retain.attributes.clone())
  99. .build(),
  100. Operation::Insert(insert) => {
  101. if interval.start > insert.count_of_utf16_code_units() {
  102. OpBuilder::insert("").build()
  103. } else {
  104. // let s = &insert
  105. // .s
  106. // .chars()
  107. // .skip(interval.start)
  108. // .take(min(interval.size(), insert.count_of_code_units()))
  109. // .collect::<String>();
  110. let s = insert.s.sub_str(interval);
  111. OpBuilder::insert(&s).attributes(insert.attributes.clone()).build()
  112. }
  113. },
  114. };
  115. match op.is_empty() {
  116. true => None,
  117. false => Some(op),
  118. }
  119. }
  120. pub fn is_delete(&self) -> bool {
  121. if let Operation::Delete(_) = self {
  122. return true;
  123. }
  124. false
  125. }
  126. pub fn is_insert(&self) -> bool {
  127. if let Operation::Insert(_) = self {
  128. return true;
  129. }
  130. false
  131. }
  132. pub fn is_retain(&self) -> bool {
  133. if let Operation::Retain(_) = self {
  134. return true;
  135. }
  136. false
  137. }
  138. pub fn is_plain(&self) -> bool {
  139. match self {
  140. Operation::Delete(_) => true,
  141. Operation::Retain(retain) => retain.is_plain(),
  142. Operation::Insert(insert) => insert.is_plain(),
  143. }
  144. }
  145. }
  146. impl<T> fmt::Display for Operation<T>
  147. where
  148. T: Attributes,
  149. {
  150. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  151. f.write_str("{")?;
  152. match self {
  153. Operation::Delete(n) => {
  154. f.write_fmt(format_args!("delete: {}", n))?;
  155. },
  156. Operation::Retain(r) => {
  157. f.write_fmt(format_args!("{}", r))?;
  158. },
  159. Operation::Insert(i) => {
  160. f.write_fmt(format_args!("{}", i))?;
  161. },
  162. }
  163. f.write_str("}")?;
  164. Ok(())
  165. }
  166. }
  167. #[derive(Clone, Debug, Eq, PartialEq)]
  168. pub struct Retain<T: Attributes> {
  169. // #[serde(rename(serialize = "retain", deserialize = "retain"))]
  170. pub n: usize,
  171. // #[serde(skip_serializing_if = "is_empty")]
  172. pub attributes: T,
  173. }
  174. impl<T> fmt::Display for Retain<T>
  175. where
  176. T: Attributes,
  177. {
  178. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  179. if self.attributes.is_empty() {
  180. f.write_fmt(format_args!("retain: {}", self.n))
  181. } else {
  182. f.write_fmt(format_args!("retain: {}, attributes: {}", self.n, self.attributes))
  183. }
  184. }
  185. }
  186. impl<T> Retain<T>
  187. where
  188. T: Attributes,
  189. {
  190. pub fn merge_or_new(&mut self, n: usize, attributes: T) -> Option<Operation<T>> {
  191. tracing::trace!(
  192. "merge_retain_or_new_op: len: {:?}, l: {} - r: {}",
  193. n,
  194. self.attributes,
  195. attributes
  196. );
  197. if self.attributes == attributes {
  198. self.n += n;
  199. None
  200. } else {
  201. Some(OpBuilder::retain(n).attributes(attributes).build())
  202. }
  203. }
  204. pub fn is_plain(&self) -> bool { self.attributes.is_empty() }
  205. }
  206. impl<T> std::convert::From<usize> for Retain<T>
  207. where
  208. T: Attributes,
  209. {
  210. fn from(n: usize) -> Self {
  211. Retain {
  212. n,
  213. attributes: T::default(),
  214. }
  215. }
  216. }
  217. impl<T> Deref for Retain<T>
  218. where
  219. T: Attributes,
  220. {
  221. type Target = usize;
  222. fn deref(&self) -> &Self::Target { &self.n }
  223. }
  224. impl<T> DerefMut for Retain<T>
  225. where
  226. T: Attributes,
  227. {
  228. fn deref_mut(&mut self) -> &mut Self::Target { &mut self.n }
  229. }
  230. #[derive(Clone, Debug, Eq, PartialEq)]
  231. pub struct Insert<T: Attributes> {
  232. // #[serde(rename(serialize = "insert", deserialize = "insert"))]
  233. pub s: FlowyStr,
  234. // #[serde(skip_serializing_if = "is_empty")]
  235. pub attributes: T,
  236. }
  237. impl<T> fmt::Display for Insert<T>
  238. where
  239. T: Attributes,
  240. {
  241. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  242. let mut s = self.s.clone();
  243. if s.ends_with('\n') {
  244. s.pop();
  245. if s.is_empty() {
  246. s = "new_line".into();
  247. }
  248. }
  249. if self.attributes.is_empty() {
  250. f.write_fmt(format_args!("insert: {}", s))
  251. } else {
  252. f.write_fmt(format_args!("insert: {}, attributes: {}", s, self.attributes))
  253. }
  254. }
  255. }
  256. impl<T> Insert<T>
  257. where
  258. T: Attributes,
  259. {
  260. pub fn count_of_utf16_code_units(&self) -> usize { self.s.utf16_size() }
  261. pub fn merge_or_new_op(&mut self, s: &str, attributes: T) -> Option<Operation<T>> {
  262. if self.attributes == attributes {
  263. self.s += s;
  264. None
  265. } else {
  266. Some(OpBuilder::<T>::insert(s).attributes(attributes).build())
  267. }
  268. }
  269. pub fn is_plain(&self) -> bool { self.attributes.is_empty() }
  270. }
  271. impl<T> std::convert::From<String> for Insert<T>
  272. where
  273. T: Attributes,
  274. {
  275. fn from(s: String) -> Self {
  276. Insert {
  277. s: s.into(),
  278. attributes: T::default(),
  279. }
  280. }
  281. }
  282. impl<T> std::convert::From<&str> for Insert<T>
  283. where
  284. T: Attributes,
  285. {
  286. fn from(s: &str) -> Self { Insert::from(s.to_owned()) }
  287. }
  288. impl<T> std::convert::From<FlowyStr> for Insert<T>
  289. where
  290. T: Attributes,
  291. {
  292. fn from(s: FlowyStr) -> Self {
  293. Insert {
  294. s,
  295. attributes: T::default(),
  296. }
  297. }
  298. }